如何使用Rails路由从一个域重定向到另一个域?
我的应用程序曾经在foo.tld上运行,但现在它在bar.tld上运行。 对于foo.tld,仍然会有请求,我想将它们重定向到bar.tld。
我怎样才能在rails路线中这样做?
这适用于Rails 3.2.3
constraints(:host => /foo.tld/) do match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"} end
这适用于Rails 4.0
constraints(:host => /foo.tld/) do match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}, via: [:get, :post] end
这完成了另一个答案的工作。 此外,它还保留了查询字符串 。 (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
注意:如果您要处理的是完整域而不仅仅是子域,请使用:domain而不是:host。
以下解决方案在GET
和HEAD
请求上重定向多个域,同时在所有其他请求上返回http 400(根据类似问题中的此注释 )。
/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
由于某种原因, constraints Constraints::DomainRedirectConstraint.new do
对我没有用于heroku但是constraints: Constraints::DomainRedirectConstraint.new
工作得很好。