December, 11 2019

How To Redirect To HTTPS Using Laravel Middleware

I believe this is not your first time of hearing about HTTP & HTTPS. These two are transfer protocols for the web.

There are lots of articles out there that explains why HTTPS is highly recommended but I will summarize it this way: HTTPS is a secured version of HTTP. So if you care about the security of your web application you need to care about HTTPS.

Laravel Middleware

According to Laravel documentation, middleware provide a convenient mechanism for filtering HTTP requests entering your application.

So there are lots of things that you can do with middleware but for this tutorial we are going to check if any HTTP request is entering our application and them force it to use HTTPS.

I am assuming you already have a Laravel app where you want to apply this.

Note: You need to install SSL certificate (like LetsEncrypt) on the server running your app before you continue with this tutorial!

Lets Start!

Disclaimer: This is just a work around I use to avoid going through the inconvenience that .htaccess file can bring.

Create your SecuredHttp middleware class using this command:

php artisan make:middleware SecuredHttp

All Laravel middleware can be found on this path: app\Http\Middleware

Now lets add our redirection logic inside our middleware . All HTTP requests coming into Laravel middleware are handled inside the handle() method.

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

Our logic is pretty simple. It checks for unsecured request and redirect it back to the same path that is secured (HTTPS).

Now we are going to register our SecuredHttp middleware class as a global middleware. This will allow it to run on every HTTP request coming into our application.

Update $middleware property of your app/Http/Kernel.php class like this:

protected $middleware = [
   ....
   \App\Http\Middleware\SecuredHttp::class,
   ....
];

Now your SecuredHttpmiddleware is actively waiting for HTTP requests that will near your app :)

Conclusion

I just showed you one out of a million things you can do with Laravel middleware.

You can also follow me on twitter @stephenjude_

Join my inner circle newsletter

Be the first to hear about anything I publish, launch, or think is helpful for you. Subscribe here

Hey, have you tried Litehost lately ?

Litehost is a web hosting platform for PHP & Laravel developers with Composer, Git, PHP & CLI pre-installed. Try it now