Rails 301从/ de重定向到/ de /

时间:2018-12-28 09:04:34

标签: ruby-on-rails ruby routes http-status-code-301

我如何从

进行重定向

http://bla.com/dehttp://bla.com/de/

我尝试过

get '/de', to: redirect('de/', status: 301)


get "/de" => redirect("/de/")

但是我有一个错误 错误:重定向过多

我的错误在哪里?

 [Anonymous user] Started GET "/de" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200
[Anonymous user] Started GET "/de/" for 127.0.0.1 at 2018-12-28 11:03:15 +0200

1 个答案:

答案 0 :(得分:1)

首先,滑轨不会区分正斜线还是尾斜线。这就是为什么您收到太多重定向错误的原因。

一种实现此目的的方法是在ApplicationController中定义一个方法,然后将其用作过滤器来重定向您的请求

def force_trailing_slash
    redirect_to request.original_url + '/' unless request.original_url.match(/\/$/)
end

或者您可以使用机架重写在机架级别的Rails应用中执行相同的任务。

https://github.com/jtrupiano/rack-rewrite

config.middleware.insert_before 0, Rack::Rewrite do
  r301 '/de', '/de/'
end

另一种可能有用的方法是:

get '/de', :to => redirect('de/'), :constraints => lambda {|r| !r.original_fullpath.end_with?('/')}

希望这会有所帮助!