How do I redirect without www using Rails 3 / Rack? How do I redirect without www using Rails 3 / Rack? ruby-on-rails ruby-on-rails

How do I redirect without www using Rails 3 / Rack?


In Ruby on Rails 4, removing www. from any URL whilst maintaining the pathname can be achieved simply by using:

# config/routes.rbconstraints subdomain: 'www' do  get ':any', to: redirect(subdomain: nil, path: '/%{any}'), any: /.*/end

In contrast, adding www. to the beginning of any URL that doesn't already have it can be achieved by:

# config/routes.rbconstraints subdomain: false do  get ':any', to: redirect(subdomain: 'www', path: '/%{any}'), any: /.*/end


There's a better approach if you're using Rails 3. Just take advantage of the routing awesomeness.

Foo::Application.routes.draw do  constraints(:host => /^example.com/) do    root :to => redirect("http://www.example.com")    match '/*path', :to => redirect {|params| "http://www.example.com/#{params[:path]}"}  endend


I really like using the Rails Router for such things. Previous answers were good, but I wanted something general purpose I can use for any url that starts with "www".

I think this is a good solution:

constraints(:host => /^www\./) do  match "(*x)" => redirect { |params, request|    URI.parse(request.url).tap {|url| url.host.sub!('www.', '') }.to_s  }end