How to force HTTPS scheme in Laravel?

Overview

Hypertext Transfer Protocol Secure (HTTPS) is the secure version of HTTP. This is important when users are transmitting sensitive data. The browsers we use to access a website these days flag the website as insecure if it has an insecure URL like http://example.com/home.

To have HTTPS in our website we need to purchase and install an SSL certificate for our website first.

We can use any of the two processes mentioned below to force redirect an HTTP URL to HTTPS in Laravel If the website does not redirect to HTTPS by default.

Steps to force HTTPS scheme in Laravel

Process 1: Using URL facade in service providers

We will simply modify the boot function of the App\Providers\AppServiceProvider.php file to force redirect:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\URL;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        $this->app['request']->server->set('HTTPS', true);
	URL::forceScheme('https');
    }
}

This will redirect all HTTP URLs to HTTPS URLs. This will also work for Javascript and CSS references.

Process 2: Using Middleware

We can create the middleware by using the following artisan command:

php artisan make:middleware ForceHttpsMiddleware

The above command will generate ForceHttpsMiddleware.php in the app/Http/Middleware directory.

Then we will modify the handle method of the ForceHttpsMiddleware class. Here we will check if the request is using HTTP then we will redirect to the same URI using HTTPS.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class ForceHttpsMiddleware
{    
    public function handle($request, Closure $next)
    {
        if (!$request->secure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Now we will add the created middleware within the $middlewareGroups property of the Kernel.php file located at the App/Http directory.

protected $middlewareGroups = [
    'web' => [
       //...
       \App\Http\Middleware\ForceHttpsMiddleware::class,
    ],

    'api' => [
        // ...
    ],
];

The ForceHttpsMiddleware middleware will redirect all the requests that are handled by Laravel routes.