Skip to content

How to redirect requests to HTTPS in Laravel 5

Last updated on February 17, 2018

I know we can achieve same with other methods but I am going do it with the Laravel’s Middleware. So let’s create Middleware called ForceHttpProtocol.

How it will work

Our ForceHttpProtocol middleware will redirect every request to https if – The current request comes with no security protocol means HTTP and If your environment is equaled to prod. So, just adjust the settings according to your preferences.

Create middleware

Using your Terminal, navigate to your project’s root directory and issue the following artisan command:

 $ php artisan make:middleware ForceHttpProtocol

Now, using your editor of choice, change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it look like this:

secure() && env('APP_ENV') === 'pro') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }

}

Next update /app/Http/Kernel.php adding the 'App\Http\Middleware\ForceHttpProtocol' instruction which will make Laravel aware of your custom middleware:

    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\ForceHttpProtocol'

    ];

If you want to apply middleware only on specific routes you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'forceSsl' => App\Http\Middleware\ForceHttpProtocol::class,

];

If route middleware – just use your middleware as you’re used to:

Route::get('projects', ['middleware' => 'forceSsl', function()
{
   echo 'Hello, I am secure';
}]);

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments