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)
与其他答案类似,这个对我有用:
# 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)
这完成了另一个答案的工作.此外,它还保留了查询字符串.(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.
更现代的方法:
constraints(host: 'www.mydomain.com') do
get '/:param' => redirect('https://www.mynewurl.com/:param')
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11340 次 |
| 最近记录: |