Redirect HTTP To HTTPS Using Laravel Middleware

Published on December 20, 2019 36 sec read

There are many ways to redirect the user HTTP to HTTPS. We can redirect using .htaccess, Nginx config etc. Today we’re going to do this using Laravel middleware. I am assuming you’ve already installed SSL on your server or your web hosting provides SSL. So lets’ start.

The Process

We need to create a middleware. Let’s create a middleware named SecuredHttp:

php artisan make:middleware SecuredHttp

Go to app\Http\Middleware folder and open SecuredHttp.php file. We’re going to modify the handle() method. Just copy & paste this code:

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

This middleware will check unsecured requests and will redirect to secured protocol.

We need to do one more thing. We need to register the newly created middleware in Kernel. Open app/Http/Kernel.php file and in $middleware array just include the middleware like this:

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

That’s it. Now all unsecured requests will be redirected to secured protocol. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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