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,
Be the first one to write a response :(
{{ reply.member.name }} - {{ reply.created_at_human_readable }}