How to Force SSL (HTTPS) in Laravel

March 10, 2020

Out of the box, Laravel will allow both HTTPS and HTTP requests to your website or application. Ideally all requests are served via SSL. There are several ways to accomplish this, some of which require access to server configs. I am going to show you how you can easily force SSL in your Laravel application to ensure HTTPS will be on no matter where you application is deployed. Of course the server still requires a valid SSL certificate to run- that is outside the scope of this tutorial.

Assumptions

  • Working server with the SSL certificate already installed
  • Laravel app running
  • Requests being fulfilled on both HTTP and HTTPS
  • Basic Laravel knowledge

Time to complete in your app

30 minutes or less!

How it works

Laravel provides a mechanism for filtering HTTP requests called Middleware. Middleware has many use cases, a few of which include: user verification, CORS headers, logging requests, etc. Only after all Middleware conditions have been met is the app able to fulfill the visitor’s request. This is the perfect place for us to enforce SSL.

Read more about Middleware in the on the official Laravel docs https://laravel.com/docs/master/middleware

Step One: Create the Middleware Base

Middleware can be generated automatically with artisan with the following command:

php artisan make:middleware ForceSSL

The new file will be created in app/Http/Middleware/ForceSSL.php

namespace App\Http\Middleware;

use Closure;

class ForceSSL
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Step Two: Update the handler

All we have to do now is look at the request and if it is not secure redirect to the secure version of the url!

Update the handle method like so

    public function handle($request, Closure $next)
    {

        // If the request is not secure, redirect to the HTTPS url.
        if( !$request->secure() ) {
            return redirect()->secure( $request->getRequestUri() );
        }

        // Otherwise carry on.
        return $next($request);
    }

Step Three: Test

That is it. 

Really.

Go test it.

Step Four: Enjoy a nice scotch

‘nuff said

Photo by Anita Jankovic on Unsplash

Leave a Reply

Your email address will not be published. Required fields are marked *