Laravel Middleware 301 Redirect, from http to https or non-www to www site redirect


Image title


Recently I set my production Laravel site protocol from http to https and set my preferred version in google web master account as www version as http://www.mysite.com instead of http://mysite.com,

since my site is already deployed long time back to production server, I needed to make a global redirect for all URL routes to avoid already indexed SEO contents conflicts and to improve Search engine optimization further, Google SEO prefers https laravel site more than non http laravel sites,
So I came up with the following Laravel Middleware,

public function handle($request, Closure $next)
    {
        if(config('app.env') == 'production'){

            $host = $request->header('host');
            if (substr($host, 0, 4) != 'www.') {
                if(!$request->secure()){
                    $request->server->set('HTTPS', true);
                }
                $request->headers->set('host', 'www.'.$host);
                return Redirect::to($request->path(),301);
            }else{
                if(!$request->secure()){
                    $request->server->set('HTTPS', true);
                    return Redirect::to($request->path(),301);
                }
            }
        }

        return $next($request);
    }

Let me explain what the code does,
simply first block of if else condition, checks whether application environment is production, and if non www access,  so it changes the host to www and also make sure the protocol is https,
second block of if/else condition executed when my visitors try to access the site with www version but http protocol, so its simply set the protocol as https, 

Written by Akram Wahid 6 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}