Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    });

});
like image 508
Port 8080 Avatar asked Nov 05 '14 09:11

Port 8080


People also ask

How do I forward a URL without www?

Press the Create Page Rule button. Type in your current website URL without the www, then set the page rule as Forwarding URL. Select 301 – Permanent Redirect as the status code.

Do I need to redirect to non-www?

For most users, it is not of particular importance whether they access a website via a www or a non-www link. However, the fact that a website is accessible with or without the input of “www” can seriously impact a website's search engine ranking.


1 Answers

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.'.

like image 138
Paulo Renato Dias Avatar answered Sep 29 '22 08:09

Paulo Renato Dias