问题描述
如何将错误的 url 重定向到 routes.rb 中的 404 页面?现在我使用 2 个示例代码:
How can I redirect incorrect url to 404 page in routes.rb?Now I use 2 examples code:
# 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/
But when I try using russian words in 'url' parameter, in 1st example I get 500 page (bad URI), in 2nd - I get redirect to stage.example.xn--org-yedaaa1fbbb/
谢谢
推荐答案
如果您想要自定义错误页面,最好查看 这个答案我几周前写的
If you want custom error pages, you'll be best looking at this answer I wrote a few weeks ago
您需要几个重要的元素来创建自定义错误路由:
You need several important elements to create custom error routes:
-> 在application.rb
中添加自定义错误处理程序:
-> Add custom error handler in application.rb
:
# File: config/application.rb
config.exceptions_app = self.routes
-> 在您的 routes.rb
中创建 /404
路由:
-> Create /404
routes in your routes.rb
:
# File: config/routes.rb
if Rails.env.production?
get '404', :to => 'application#page_not_found'
end
-> 将 actions
添加到应用程序控制器以处理这些路由
-> Add actions
to application controller to handle these routes
# 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
这显然是相对基本的,但希望它能给你更多关于你能做什么的想法
This is obviously relatively basic, but hopefully it will give you some more ideas on what you can do
这篇关于如何重定向到routes.rb 中的404 页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!