Port 8080 Port 8080 - 4 months ago 11
PHP Question

Redirect www to non-www in Laravel with URL parameters

How can I redirect URL from

www.myapp.co
to
myapp.co
? And also if the URL has other parameter like
www.myapp.co/other-parameter
will be redirected to
myapp.co/other-parameter
where the
other-parameter
can be anything. Sorry for this noob question, I am still 1 week in using Laravel.

BTW, I am using dynamic subdomain so I need only the redirect www to non-www and not the other subdomains.

Route::group(array('domain' => 'myapp.co'), function() {

Route::get('/', function() {
return 'Hello! Welcome to main page...';
});
Route::get('/login', function() {
return 'Login';
});
Route::get('/signup', function() {
return 'Signup';
});

});

Route::group(array('domain' => '{account}.myapp.co'), function() {

Route::get('/', function($account) {

if ($account == 'www') {
return Redirect::to('http://myapp.co');
}
return $account;
});

});

Answer

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)

Comments