2017-09-21 61 views
1

這是我目前的處理錯誤的植入:如何在不重定向的情況下在Rails 4中顯示404頁面?

#routes.rb 
match "/404", :to => "errors#not_found", :via => :all, as: 'not_found' 
match "/500", :to => "errors#internal_server_error", :via => :all 

#ErrorsController.rb 
class ErrorsController < ApplicationController 
    def not_found 
    render(:status => 404) 
    end 

    def internal_server_error 
    render(:status => 500) 
    end 
end 

#views/errors/not_found.html.erb 
(static HTML page) 

我的問題是,當我在我的網站上輸入了錯誤的URL,如www.example.com/asdfasdf,我重定向到www.example.com/404。爲了便於比較,如果我訪問www.stackoverflow.com/asdfasdf,我收到了'找不到頁面'的錯誤,但URL仍然顯示爲www.stackoverflow.com/asdfasdf。

我想改變它的行爲方式,使它與Stack Overflow中的工作方式相匹配,我在那裏顯示了404頁面,但URL仍然與我鍵入的內容相同。什麼是最好的方式來做到這一點?謝謝!

回答

2

試試這個:

# routes.rb 
match "/404", :to => "errors#not_found", :via => :all, as: 'not_found' 
match "/500", :to => "errors#internal_server_error", :via => :all 

# errors_controller.rb 
class ErrorsController < ApplicationController 
    def not_found 
    render :file => 'public/404.html', :status => :not_found, :layout => false 
    end 

    def internal_server_error 
    render :file => 'public/500.html', :status => :not_found, :layout => false 
    end 
end 
相關問題