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

如何将不正确的URL重定向到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-yedaa​​a1fbbb /

谢谢

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


您需要几个重要元素来创建自定义错误路径:

– > 在application.rb中添加自定义error handling程序:

 #config/application.rb config.exceptions_app = self.routes 

– > routes.rb文件中创建/404路由:

 config/routes.rb if Rails.env.production? get '404', :to => 'application#page_not_found' end 

– > 向应用程序控制器添加actions以处理这些路由

 #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 

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

最简单的方法是确保您的路由与坏URL不匹配。 默认情况下,Rails将为不存在的路由返回404。

如果您无法执行此操作,则默认404页面位于/404因此您可以重定向到该位置。 但是,要记住的是,这种类型的重定向将执行301永久重定向而不是302.这可能不是您想要的行为。 为此,您可以执行以下操作:

 match "/go/(*url)", to: redirect('/404') 

相反,我建议您在操作中设置一个前置filter,而不是引发一个未找到的exception。 我不确定这个exception是否在Rails 4中的相同位置,但是使用Rails 3.2我正在使用:

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

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