How to Redirect Laravel from HTTP to HTTPS

After installing an SSL certificate, the next step is redirecting your traffic from HTTP to HTTPS. That’s a lot easier in simple PHP websites but for Laravel websites, we are going to follow the code snippets below.

Make Middleware for Redirect

Create file in \app\Http\Middleware\HttpsProtocol.php . Open file HttpsProtocol.php and write the following code.

<?php
namespace App\Http\Middleware;

use Illuminate\Support\Facades\App;
use Closure;

class HttpsProtocol {
    public function handle($request, Closure $next) {
        if ( App::environment(['staging', 'production']) && !$request->secure() ) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Connect in Kernel.php

Open file \app\Http\Kernel.php and add line \App\Http\Middleware\HttpsProtocol::class, in the middlewareGroups array.

<?php

    // some existing code

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\HttpsProtocol::class, // add line here at the end
        ],

    ];

Define Environment

Open .env file and specify the environment, we are only redirection on staging and production environment.

APP_ENV=production

Now your Laravel application is served on https for production and staging environments.


4 comments

Leave a comment

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