Routing constraints make this really easy. Here's one for each option.
These will redirect all URLs and the root path too. They would need to be the first routes in your routes file to work.
# Remove www with redirect
# Add www with redirect but only on production
if Rails.env.production?
constraints subdomain: 'www' do
get ":any", to: redirect(subdomain: nil, path: "/%{any}"), any: /.*/
root to: redirect(subdomain: nil, path: "/"), as: :www_root
end
end
# Add www with redirect but only on production
if Rails.env.production?
constraints subdomain: false do
get ":any", to: redirect(subdomain: "www", path: "/%{any}"), any: /.*/
root to: redirect(subdomain: "www", path: "/"), as: :non_www_root
end
endYou could also do this in Rack Middleware before it makes it to Rails as well.