How to redirect to 404 page in routes.rb?

How to redirect the wrong url to page 404 in routes.rb? Now I use 2 code examples:

# 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 

But when I try to use Russian words in the "url" parameter, in the first example I get 500 pages (bad URI), in the second I get a redirect to stage.example.xn - org-yedaaa1fbbb /

thanks

+6
source share
2 answers

If you want to create your own pages with errors, you are best off looking at this answer. I wrote a few weeks ago


You need a few important elements to create custom error routes:

-> Add a custom error handler to application.rb:

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

-> Create routes /404 in your routes.rb :

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

-> Add actions to the application controller to handle these routes

 #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 solid, but hopefully it will give you some more ideas on what you can do.

+18
source

The simplest task is to make sure your routes do not match bad URLs. By default, Rails will return 404 for routes that do not exist.

If you cannot do this, the 404 page is located at /404 by default, so you can redirect to that location. However, here it should be borne in mind that this type of redirect will perform 301 Permanent redirects instead of 302. This may not be the behavior you want. To do this, you can do the following:

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

Instead, I would recommend setting up a filter in my action before that, which instead throws an exception not found. I'm not quite sure that this exception is in the same place in Rails 4, but with Rails 3.2 I currently use:

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

Then you can perform any processing and verification of URLs in the controller (if complex verification of the URL format is required).

+2
source

Source: https://habr.com/ru/post/956927/


All Articles