Redirect HTTP To HTTPS Using Laravel Middleware

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 = [

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