How can I use Rails routes to redirect from one do

2019-01-11 01:59发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

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.