I understand there are a lot of questions that answer this. I\'m familiar with .htaccess
and nginx.conf
methods, but I do not have access to such t
Take a look at this middleware, it should do precisely what you want:
http://github.com/iSabanin/www_ditcher
Let me know if that worked for you.
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]}"}
end
end
In Rails 3
#config/routes.rb
Example::Application.routes.draw do
constraints(:host => "www.example.net") do
match "(*x)" => redirect { |params, request|
URI.parse(request.url).tap { |x| x.host = "example.net" }.to_s
}
end
# ....
# .. more routes ..
# ....
end
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
A one-line version of Duke's solution. Just add to the top of routes.rb
match '(*any)' => redirect { |p, req| req.url.sub('www.', '') }, :constraints => { :host => /^www\./ }
For Rails 4 the above solutions have to be appended with the Verb construction e.g. via: [:get, :post]
. Duke's solution becomes:
constraints(:host => /^www\./) do
match "(*x)" => redirect { |params, request|
URI.parse(request.url).tap {|url| url.host.sub!('www.', '') }.to_s
}, via: [:get, :post]
end