22

私のアプリは以前はfoo.tldで実行されていましたが、現在はbar.tldで実行されています。foo.tldに対するリクエストは引き続き受信されますが、bar.tldにリダイレクトしたいと思います。

Railsルートでこれを行うにはどうすればよいですか?

4

6 に答える 6

43

これは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
于 2012-06-06T17:32:24.227 に答える
6

これは、他の答えの仕事をします。さらに、クエリ文字列も保持します。(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 を使用してください。

于 2014-12-01T01:06:20.817 に答える
3

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

于 2015-06-08T20:41:29.903 に答える