Rails: redirect all unknown routes to root_url

后端 未结 5 1600
粉色の甜心
粉色の甜心 2020-11-30 23:02

Whenever a user hits the wrong page, rails shows 404.html from the public folder. However, I\'d like just to redirect the browser to the root page, without showing anything.

相关标签:
5条回答
  • 2020-11-30 23:25

    You need create a controller to do that

    class RedirectsController 
    
      def index
        redirect_to root_url
      end
    end
    

    And in your routes

    map.connect '*', :controller => 'redirects', :action => 'index'
    
    0 讨论(0)
  • 2020-11-30 23:28

    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?
    
    0 讨论(0)
  • 2020-11-30 23:32

    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('/')
    
    0 讨论(0)
  • 2020-11-30 23:50

    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.

    0 讨论(0)
  • 2020-11-30 23:50

    There seems to be a bug in rails 5.2 where active_storage routes are picked up by the catchall route, resulting in broken links to uploaded images. The issue has been reported in the rails repo on github, and someone commented with the below patch until the bug gets fixed in a new release:

    In routes.rb right before last end

    get '*all', to: 'application#index', constraints: lambda { |req|
        req.path.exclude? 'rails/active_storage'
      }
    

    then in the application controller add:

    def index
      flash.notice = 'No page found at that address'
      redirect_to root_path
    end
    
    0 讨论(0)
提交回复
热议问题