如何在routes.rb中重定向到404页面?

10

我应该如何在routes.rb中将错误的url重定向到404页面?现在我有两个示例代码:

# 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/。
谢谢。

你能提供一些你正在尝试使用的示例URL吗? - dnch
一些示例:stage.example.org/go/газета stage.example.org/go/газета.рф - piton4eg
如果您想从控制器内部重定向到404页面,您也可以使用redirect_to("/404") && return - dcts
2个回答

30

如果您想要自定义错误页面,最好查看我几周前写的这个答案


要创建自定义错误路由,您需要以下几个重要元素:

-> application.rb中添加自定义错误处理程序:

# File: config/application.rb
config.exceptions_app = self.routes
在你的routes.rb中创建/404路由:
# 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

这显然是相对基础的,但希望它能给你一些更多关于你可以做什么的想法。


5
最简单的做法是确保您的路由不匹配错误的URL。 默认情况下,Rails将返回不存在的路由的404错误。
如果您无法做到这一点,默认的404页面位于/404,因此您可以重定向到该位置。 但是,请注意,这种重定向将执行301永久重定向,而不是302。 这可能不是您想要的行为。 为此,您可以执行以下操作:
match "/go/(*url)", to: redirect('/404')

相反,我建议在你的操作中设置一个before过滤器(before filter),这样会引发一个未找到异常(not found exception)。我不确定这个异常在Rails 4中是否在同一位置,但是在Rails 3.2中,我目前使用的是:

raise ActionController::RoutingError.new('Not Found')

如果需要对URL格式进行复杂的检查,您可以在控制器中进行任何处理和URL检查。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接