
Automatically adding the HSTS header in Laravel
7 Jul 2022 #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:
<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request;use Illuminate\Support\Facades\App; class HSTS{ public function handle(Request $request, Closure $next) { $response = $next($request); if (!App::environment('local')) { $response->headers->set( 'Strict-Transport-Security', 'max-age=31536000; includeSubdomains', true ); } return $response; }}
After that, it's a matter of enabling it in the app/Http/Kernel.php
file under the key $middleware
:
namespace App\Http; use App\Http\Middleware\AllowedRolesMiddleware;use App\Http\Middleware\ApiVersioning;use App\Http\Middleware\IsAuthorized;use App\Http\Middleware\PassportClientIsAuthorizedForCompany;use Fruitcake\Cors\HandleCors;use Illuminate\Foundation\Http\Kernel as HttpKernel;use Laravel\Passport\Http\Middleware\CheckClientCredentials; class Kernel extends HttpKernel{ /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ HandleCors::class, \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \App\Http\Middleware\InvalidDateCleaner::class, \App\Http\Middleware\HSTS::class, // <- add this line ]; // ...}
Note: in this example, I've disabled this for the local
environment as I'm using Laravel Valet for testing over http (not https).