It is probably not a good idea to have your website reachable from both “www.” URL as well as “non-www” top-level URL. As this diverts traffic (and bookmarks) to two different URIs while also possibly splitting up search-engine’s page-ranking. While “www.” URLs have their own advantages (e.g., familiarity, cookie-less sibling subdomain), non-www URLs take at least one less DNS query to resolve and are shorter.
Here is how to achieve the redirection in Rails 3:
# config/routes.rb
constraints(:host => "www.example.net") do
# Won't match root path without brackets around "*x". (using Rails 3.0.3)
match "(*x)" => redirect { |params, request|
URI.parse(request.url).tap { |x| x.host = "example.net" }.to_s
}
end
And the reverse i.e., redirecting “without-www” to “www”:
# config/routes.rb
constraints(:host => "example.net") do
match "(*x)" => redirect { |params, request|
URI.parse(request.url).tap { |x| x.host = "www.example.net" }.to_s
}
end




Does it works on last versions of Rails?
Could it be modified to be domain agnostic?
Hi,
It works on the last 3.x version of rails.
Also it can be domain agnostic. Here is domain agnostic version for this:
# config/routes.rb constraints(subdomain: '') do match "(*x)" => redirect do |params, request| URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s end endoops: little mistake
here it is:
Hi, It works on the last 3.x version of rails. Also it can be domain agnostic. Here is domain agnostic version for this: 1 2 3 4 5 6 # config/routes.rb constraints(subdomain: '') do match "(*x)" => redirect { |params, request| URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s } endHate when I can't edit my posts :) :)