如何使用Rails路由从一个域重定向到另一个域?

Joh*_*hir 20 routing ruby-on-rails rails-routing

我的应用程序曾经在foo.tld上运行,但现在它在bar.tld上运行.请求仍然会出现在foo.tld中,我想将它们重定向到bar.tld.

如何在rails路由中执行此操作?

Luk*_*und 42

这适用于Rails 3.2.3

constraints(:host => /foo.tld/) do
  match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}
end
Run Code Online (Sandbox Code Playgroud)

这适用于Rails 4.0

constraints(:host => /foo.tld/) do
  match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"},  via: [:get, :post]
end
Run Code Online (Sandbox Code Playgroud)

  • 使用//而不是http://来确保重定向与协议无关,适用于http和https. (8认同)

sch*_*pet 6

与其他答案类似,这个对我有用:

# config/routes.rb
constraints(host: "foo.com", format: "html") do
  get ":any", to: redirect(host: "bar.com", path: "/%{any}"), any: /.*/
end
Run Code Online (Sandbox Code Playgroud)


Ami*_*ana 5

这完成了另一个答案的工作.此外,它还保留了查询字符串.(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
Run Code Online (Sandbox Code Playgroud)

注意:如果您要处理的是完整域而不仅仅是子域,请使用:domain而不是:host.

  • 实际上``http://bar.tld# {req.fullpath}"`因为`req.fullpath`已经包含前导正斜杠. (2认同)

Don*_*nMB 2

更现代的方法:

constraints(host: 'www.mydomain.com') do
  get '/:param' => redirect('https://www.mynewurl.com/:param')
end
Run Code Online (Sandbox Code Playgroud)