私のアプリは以前はfoo.tldで実行されていましたが、現在はbar.tldで実行されています。foo.tldに対するリクエストは引き続き受信されますが、bar.tldにリダイレクトしたいと思います。
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
注: サブドメインだけでなく完全なドメインを扱う場合は、:host の代わりに :domain を使用してください。
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
。