Rails redirects invalid route to root directory

If my site is www.foo.com , if the user types www.foo.com/blahblahblah , he will say that /blahblahblah is an invalid path (obviously). But I want it to be redirected to root_path instead, so that the controller can handle the URL - the page www.foo.com should be displayed. I want to pull out the text blahblahblah and do something with it. How to do it?

+7
source share
2 answers

There are several possibilities. Here is one. You can add this to the bottom of your .rb routes:

 match ':not_found' => 'my_controller#index', :constraints => { :not_found => /.*/ } 

which sets the entire route to force the MyController index action to handle any missing paths; he can detect them by looking at params[:not_found] and doing whatever he wants, for example, redirects to root_path ( redirect_to root_url ), redirects somewhere strategically based on a bad path, something special, exploring the referrer / referent for tips about source, etc.

Requires option :constraints ; otherwise, the not_found parameter not_found not contain special characters, such as slashes and not_found .

Put this at the bottom of your routes, because obviously it will fit all, and you want your other routes to crack along the way first.

If you only want to redirect, nothing more, you can do it instead (again, at the bottom ):

 match ':not_found' => redirect('/'), :constraints => { :not_found => /.*/ } 
+8
source

on rails 4 get '* path' => redirect ('/')

+5
source

All Articles