Redirect HTTP to HTTPS using Middleware in Laravel

Hello Artisan

In this redirect HTTP to HTTPS in laravel tutorial, i will show you how we can redirect user requests automatically HTTP to HTTPS in laravel using middleware. We can do it using a .htaccess file in any application.

But in this tutorial, I will use middleware, and then every route we have to use this middleware. Use this secure connection to make your site more protectable and looks pretty in the URL bar. 

So create a middleware to make redirect HTTP to HTTPS. run below command to create it.

php artisan make:middleware HttpsProtocol​

 

After creating this middleware, update this newly created middleware like that:

App\Http\Middleware\HttpsProtocol​.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class HttpsProtocol​
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$request->secure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

 

Now we need to register our middleware before using it like below:

App\Http\Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
   
    protected $routeMiddleware = [
        'https' => \App\Http\Middleware\HttpsProtocol​::class,
    ];
}

 

And now use it like below to redirect HTTP to HTTPS in laravel using middleware:

Route::get('/', function () {
    // code goes here
})->middleware('https');

 

Now if you visit this http://127.0.0.1:8000  you will notice that HTTPS is attached to your request. 

 

Read also: Laravel Force Redirect Http to Https Using htaccess

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js