Rails: redirect all unknown routes to root_url Rails: redirect all unknown routes to root_url ruby-on-rails ruby-on-rails

Rails: redirect all unknown routes to root_url


If your project is powered by rails 3, add simply this line to your routes.rb

match '*path' => redirect('/')

Edit: If you're on Rails 4 or 5

match '*path' => redirect('/'), via: :get

or

get '*path' => redirect('/')


Like the answer by Arkan. One point, if do not want this behaviour in development environment, then could do -

match '*path' => redirect('/')   unless Rails.env.development?


Rails 4-

(routes.rb)

You can still use a simple get to redirect all unknown routes.

  get '*path', to: 'home#index'

If you wish to provide routing to both POST and GET requests you can still use match, but Rails wants you to specify the request method via via.

  match "*path" => "home#index", via: [:get, :post]  

Remember that routes.rb is executed sequentially (matching the first route that fits the supplied path structure), so put wildcard catching at the bottom of your matchings.