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?
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 => /.*/ }
in rails 4 get '*path' => redirect('/')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With