Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails redirecting invalid route to root

If my website is www.foo.com if the user types www.foo.com/blahblahblah it will say that /blahblahblah is an invalid path (obviously). But I want it instead to redirect to the root_path so that the controller can process the URL -- the page www.foo.com should be rendered I want to pull the text blahblahblah and do something with it. How do I do this?

like image 454
Kvass Avatar asked Jul 01 '11 13:07

Kvass


2 Answers

There are several possibilities. Here's one. You could add this to the bottom of your routes.rb:

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

which will establish a catch-all route to make MyController's index action handle any missing paths; it can detect them by looking at params[:not_found] and doing whatever it wants, such as redirecting to the root_path (redirect_to root_url), redirecting somewhere strategically based on the bad path, rendering something special, examining the referrer/referer for clues about the source, etc.

The :constraints option is necessary; otherwise the not_found param won't be able to contain special characters like slashes and dots.

Put this at the bottom of your routes because, obviously, it will match everything, and you want to give your other routes first crack at the path.

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

match ':not_found' => redirect('/'), :constraints => { :not_found => /.*/ }
like image 117
Rob Davis Avatar answered Oct 24 '22 15:10

Rob Davis


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

like image 37
ghanshyam Avatar answered Oct 24 '22 15:10

ghanshyam