如何将不正确的网址重定向到routes.rb中的404页面? 现在我使用2个示例代码:
# example 1
match "/go/(*url)", to: redirect { |params, request| Addressable::URI.heuristic_parse(params[:url]).to_s }, as: :redirect, format: false
# example 2
match "/go/(*url)", to: redirect { |params, request| Addressable::URI.heuristic_parse(URI.encode(params[:url])).to_s }, as: :redirect, format: false
但是当我尝试在'url'参数中使用俄语单词时,在第一个例子中我得到500页(错误的URI),在第二个 - 我被重定向到stage.example.xn - org-yedaaa1fbbb /
由于
答案 0 :(得分:23)
如果你想要自定义错误页面,你最好看几周前写的this answer
您需要几个重要元素来创建自定义错误路径:
- > 在application.rb
中添加自定义错误处理程序:
# File: config/application.rb
config.exceptions_app = self.routes
- > 在/404
routes.rb
条路线
# File: config/routes.rb
if Rails.env.production?
get '404', :to => 'application#page_not_found'
end
- > 将actions
添加到应用程序控制器以处理这些路由
# File: app/controllers/application_controller.rb
def page_not_found
respond_to do |format|
format.html { render template: 'errors/not_found_error', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
这显然是相对基础的,但希望它能为你提供更多关于你能做什么的想法
答案 1 :(得分:2)
最简单的方法是确保您的路线与错误的网址不匹配。默认情况下,Rails将为不存在的路由返回404。
如果您无法执行此操作,则默认404页面位于/404
,因此您可以重定向到该位置。但是,要记住的是,这种类型的重定向将执行301永久重定向而不是302.这可能不是您想要的行为。为此,您可以执行以下操作:
match "/go/(*url)", to: redirect('/404')
相反,我建议您在操作中设置一个前置过滤器,而不是引发一个未找到的异常。我不确定这个异常是否在Rails 4中的相同位置,但是我正在使用Rails 3.2:
raise ActionController::RoutingError.new('Not Found')
然后,您可以在控制器中进行任何处理和URL检查(如果需要复杂的URL格式检查)。