My app used to run on foo.tld but now it runs on bar.tld. Requests will still come in for foo.tld, I want to redirect them to bar.tld.
How can I do this in rails routes?
My app used to run on foo.tld but now it runs on bar.tld. Requests will still come in for foo.tld, I want to redirect them to bar.tld.
How can I do this in rails routes?
 
    
    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.
 
    
     
    
    similar to other answers, this one worked for me:
# config/routes.rb
constraints(host: "foo.com", format: "html") do
  get ":any", to: redirect(host: "bar.com", path: "/%{any}"), any: /.*/
end
 
    
    The following solution redirects multiple domains on GET and HEAD requests while returning http 400 on all other requests (as per this comment in a similar question).
/lib/constraints/domain_redirect_constraint.rb:
module Constraints
  class DomainRedirectConstraint
    def matches?(request)
      request_host = request.host.downcase
      return request_host == "foo.tld1" || \
             request_host == "foo.tld2" || \
             request_host == "foo.tld3"
    end
  end
end
/config/routes.rb:
require 'constraints/domain_redirect_constraint'
Rails.application.routes.draw do
  match "/(*path)", to: redirect {|p, req| "//bar.tld#{req.fullpath}"}, via: [:get, :head], constraints: Constraints::DomainRedirectConstraint.new
  match "/(*path)", to: proc { [400, {}, ['']] }, via: :all, constraints: Constraints::DomainRedirectConstraint.new
  ...
end
For some reason constraints Constraints::DomainRedirectConstraint.new do didn't work for me on heroku but constraints: Constraints::DomainRedirectConstraint.new worked fine.
Bit more modern approach:
constraints(host: 'www.mydomain.com') do
  get '/:param' => redirect('https://www.mynewurl.com/:param')
end
 
    
     
    
    constraints(host: /subdomain\.domain\.com/) do
  match '/(*path)' => redirect { |params, req|
    "https://www.example.com#{req.fullpath}"
  }, via: [:get, :head]
end
I use this when using custom domains on Heroku and I want to redirect from the myapp.herokuapp.com -> www.example.com.
