#development #http #laravel #php

If you want to add the Strict-Transport-Security header to all your requests in Laravel, you can easily use a custom middleware for doing so.

First, start with creating a file called app/Http/Middleware/HSTS.php and put the following content in there:

 1<?php
 2
 3namespace App\Http\Middleware;
 4
 5use Closure;
 6use Illuminate\Http\Request;
 7use Illuminate\Support\Facades\App;
 8
 9class HSTS
10{
11    public function handle(Request $request, Closure $next)
12    {
13        $response = $next($request);
14
15        if (!App::environment('local')) {
16            $response->headers->set(
17                'Strict-Transport-Security',
18                'max-age=31536000; includeSubdomains',
19                true
20            );
21        }
22
23        return $response;
24    }
25}

After that, it's a matter of enabling it in the app/Http/Kernel.php file under the key $middleware:

 1namespace App\Http;
 2
 3use App\Http\Middleware\AllowedRolesMiddleware;
 4use App\Http\Middleware\ApiVersioning;
 5use App\Http\Middleware\IsAuthorized;
 6use App\Http\Middleware\PassportClientIsAuthorizedForCompany;
 7use Fruitcake\Cors\HandleCors;
 8use Illuminate\Foundation\Http\Kernel as HttpKernel;
 9use Laravel\Passport\Http\Middleware\CheckClientCredentials;
10
11class Kernel extends HttpKernel
12{
13    /**
14     * The application's global HTTP middleware stack.
15     *
16     * These middleware are run during every request to your application.
17     *
18     * @var array
19     */
20    protected $middleware = [
21        HandleCors::class,
22        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
23        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
24        \App\Http\Middleware\TrimStrings::class,
25        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
26        \App\Http\Middleware\InvalidDateCleaner::class,
27        \App\Http\Middleware\HSTS::class, // <- add this line
28    ];
29
30    // ... 
31}

Note: in this example, I've disabled this for the local environment as I'm using Laravel Valet for testing over http (not https).