Laravel Redirect All Requests To https

Sep 25, 2017 PHP Laravel Framework
Laravel Redirect All Requests To https | Learn2torials

I love working with Laravel framework it seems to me that it is developed so that it can assists developers a lot. When you have a website running on laravel framework and you want all of non http urls to be redirected to https you can easily do that with laravel middleware concept.

What is Laravel Middleware?

Well think of this way, when a user hits url in browser he made a request to the server to serve content for given url. laravel Middleware looks at that request and decides what to do before we get to the controller.

So basically, our idea is to look at the request and if it is not https redirect current url to https using middleware. Let's do that use following command to create a middleware using your terminal:

# run this command in laravel project root dir
$ php artisan make:middleware HttpsProtocol

Above command will generate a middleware file called HttpsProtocol.php in "app/Http/Middleware/HttpsProtocol.php" with following contents:

<?php

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Well, look at the handle function it gets $request parameter. This handle function will be called before our request hits the laravel controller so this would be good place for our non-https logic.

Now, we will add a piece of code that checks to see if given request is non-https then convert it to https and redirect user to that url:

<?php

namespace App\Http\Middleware;

use Closure;

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

        return $next($request);
    }
}

That is it, $request->secure() checks to see if it is non-https request and returns true or false according then we redirect to secure url. I hope you enjoyed my tutorial.

Please subscribe to my site using newsletter section on home page to keep upto date with my latest tutorials.

Rate This Article

Tutorial on how to redirect all routes to http using laravel framework with middleware concept

4.83

About Author