Redirect www to non-www in Laravel with URL parameters

If you really want to treat your problem programmatically I think the best solution is to add the next code to your filters.php:

App::before(function($request){
   //Remove the 'www.' from all domains
   if (substr($request->header('host'), 0, 4) === 'www.') {
      $request->headers->set('host', 'myapp.co');
      return Redirect::to($request->path());
   }
});

Basically I am just creating a filter to check if the request starts with 'www.' and in this case redirecting the client to the same path without the 'www.'.


Maybe you can use a .htaccess inside thepublic folder to do the redirection.

Here is one:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{HTTP_HOST} !localhost
    RewriteCond %{HTTP_HOST} !^(.+)\.(.+)\.(.+)
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
</IfModule>

Basicaly here I'm testing if the host is not localhost and not a subdomain (form abc.xyz.tldn) before issuing a redirect to www. I'm using this sort of code in multiple projects but havn't tested it. I hope it will work out of the box.

Edit: Another way to do it without complex pattern matching is described here: Redirect non www to wwww in htaccess But this solution require you to hardcode your domain name inside the htaccess. (may or may not be a problem depending on your setup)


Add the following code to your .htaccess file:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]