Rails 将无效路由重定向到 root [英] Rails redirecting invalid route to root
问题描述
如果我的网站是 www.foo.com
如果用户输入 www.foo.com/blahblahblah
它会说 /blahblahblah
是无效路径(显然).但我希望它改为重定向到 root_path 以便控制器可以处理 URL——应该呈现页面 www.foo.com
我想拉文本 blahblahblah
> 并用它做点什么.我该怎么做?
If my website is www.foo.com
if the user types www.foo.com/blahblahblah
it will say that /blahblahblah
is an invalid path (obviously). But I want it instead to redirect to the root_path so that the controller can process the URL -- the page www.foo.com
should be rendered I want to pull the text blahblahblah
and do something with it. How do I do this?
推荐答案
有几种可能性.这是一个.您可以将其添加到 routes.rb 的底部:
There are several possibilities. Here's one. You could add this to the bottom of your routes.rb:
match ':not_found' => 'my_controller#index',
:constraints => { :not_found => /.*/ }
这将建立一个包罗万象的路由,使 MyController 的索引操作处理任何丢失的路径;它可以通过查看 params[:not_found]
并做任何它想做的事情来检测它们,例如重定向到 root_path (redirect_to root_url
),根据错误策略性地重定向某个地方路径、渲染一些特殊的东西、检查引用者/引用者以获取有关来源的线索等.
which will establish a catch-all route to make MyController's index action handle any missing paths; it can detect them by looking at params[:not_found]
and doing whatever it wants, such as redirecting to the root_path (redirect_to root_url
), redirecting somewhere strategically based on the bad path, rendering something special, examining the referrer/referer for clues about the source, etc.
:constraints
选项是必须的;否则 not_found
参数将无法包含特殊字符,如斜杠和点.
The :constraints
option is necessary; otherwise the not_found
param won't be able to contain special characters like slashes and dots.
把它放在你的路线的底部,因为很明显,它会匹配一切,你想让你的其他路线首先在路径上裂开.
Put this at the bottom of your routes because, obviously, it will match everything, and you want to give your other routes first crack at the path.
如果您只想重定向,仅此而已,您可以改为执行此操作(同样,在底部):
If you only want to redirect, nothing more, you could do this instead (again, at the bottom):
match ':not_found' => redirect('/'), :constraints => { :not_found => /.*/ }
这篇关于Rails 将无效路由重定向到 root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!