Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails redirecting www. to non-www version of site

I want to redirect the www. version to the non-www version of the site, unless it is a subdomain. (example: redirect www.puppies.com to puppies.com but don't redirect www.cute.puppies.com).

How do I accomplish this while maintaining the full request path? (example: www.puppies.com/labradors goes to puppies.com/labradors)

like image 335
Dobabeswe Avatar asked Mar 06 '14 21:03

Dobabeswe


1 Answers

In your application controller:

before_filter :redirect_subdomain

def redirect_subdomain
  if request.host == 'www.puppies.com'
    redirect_to 'http://puppies.com' + request.fullpath, :status => 301
  end
end

As @isaffe points out, you can redirect in the web server as well.

EDIT: Use permanent redirect status (301) for SEO (as suggested by @CHawk) or 307 if temporary.

like image 186
noel Avatar answered Dec 03 '22 09:12

noel