How to force redirect http to https in Laravel 7.x and 6.x ?

November 15, 2017 | Category : Laravel 5.5 Laravel 5 Laravel PHP

When i was working on my first laravel 5.5 application and i make it live and i want secure connection using ssl, i buy from hosting provider. But i was thinking how to redirect http to https of url in Laravel.

After research i found to force redirect http to https my website link. If you are using Laravel 5.5 then you can redirect http to https link using middleware. I would like to create middleware for redirect http to https link.

Here, we have to create Middleware, So simple create middleware on following path and then you have to register that middleware in Kernel.php file. So let's just follow:

Create HttpsProtocol Middleware:

Now we have to create "HttpsProtocol" middleware and we will write code of redirect http to https link. So here i written code for redirect and make only for production server. So let's create middleware.

app/Http/Middleware/HttpsProtocol.php

<?php


namespace App\Http\Middleware;


use Closure;


class HttpsProtocol {


public function handle($request, Closure $next)

{

if (!$request->secure()) {

return redirect()->secure($request->getRequestUri());

}


return $next($request);

}

}


?>

Next we have to register this middleware in Kernel.php file as bellow following code:

app/Http/Kernel.php

<?php


namespace App\Http;


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel

{

.....


/**

* The application's route middleware groups.

*

* @var array

*/

protected $middlewareGroups = [

'web' => [

\App\Http\Middleware\EncryptCookies::class,

\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

\Illuminate\Session\Middleware\StartSession::class,

// \Illuminate\Session\Middleware\AuthenticateSession::class,

\Illuminate\View\Middleware\ShareErrorsFromSession::class,

\App\Http\Middleware\VerifyCsrfToken::class,

\Illuminate\Routing\Middleware\SubstituteBindings::class,

\App\Http\Middleware\HttpsProtocol::class

],


......

];

....

}

Ok, As above i added middleware, you can add this way and now you can check your all links.

I hope you found your best solution...