Spread the love

To redirect from http to https secure url in laravel we can achieve by multiple ways. While deploying application to server we need to make our website secure and robust so attackers can not attack easily on website. In this tutorial we will learn to redirect the http to https secure url in laravel and apache too.

We will check multiple methods to redirect and all methods will work in all versions of laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

Method 1 : Redirect to https using middleware

First method is using the laravel itself by creating the custom middleware and then in handle method we will check request is secure or not. if we are developing the application on localhost then we do not want this behavior to redirect the http url to https so we will also check the app environment is local or production so here i checked the production. You can change it according to your requirement.

namespace MyApp\Http\Middleware;

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

class HttpsRedirect {

    public function handle($request, Closure $next)
    {
            if (!$request->secure() && \App::environment() === 'production') {
                return redirect()->secure($request->getRequestUri());
            }

            return $next($request); 
    }
}

And add it in kernel.php web middleware so we can redirect every request of web application to https as follow

protected $middlewareGroups = [
    'web' => [
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,

        // here
        \App\Http\Middleware\HttpsRedirect::class

    ],
];

Or you can add it to specific route group or url in web.php file.

Method 2: Redirect using htaccess file

In this method we will use htaccess to redirect from http to https so this will work out of the box

RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Here we simply enabled the RewriteEngine then checked if the request is not https then using the RewriteRule we are redirecting the request to https url.

Method 3 : Using forceScheme Method of URL Class to Redirect to Https

\URL::forceScheme('https'); is usefull while we are behind the proxy or we want to serve all interal assets urls to https then we need to resgister forceScheme in AppServiceProvider.php so it will redirect all application request to https

\URL::forceScheme('https');

and use it as below

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    
    public function register()
    {
       \URL::forceScheme('https');
    }
    public function boot()
    {
        //
    }
}

Leave a Reply