How can I use Rails routes to redirect from one domain to another?
This works in Rails 3.2.3
constraints(:host => /foo.tld/) do
match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}
end
This works in Rails 4.0
constraints(:host => /foo.tld/) do
match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}, via: [:get, :post]
end
This does the job of the other answer. Though in addition, it preserves query strings as well. (Rails 4):
# http://foo.tld?x=y redirects to http://bar.tld?x=y
constraints(:host => /foo.tld/) do
match '/(*path)' => redirect { |params, req|
query_params = req.params.except(:path)
"http://bar.tld/#{params[:path]}#{query_params.keys.any? ? "?" + query_params.to_query : ""}"
}, via: [:get, :post]
end
Note: If you're dealing with full domains instead of just subdomains, use :domain
instead of :host
.