简体   繁体   中英

How to show 404 page in Rails 4 without redirect?

this is my current implantation of handling errors:

#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)

My problem is when I enter a wrong URL in my website, such as www.example.com/asdfasdf, I get redirected to www.example.com/404. For comparison, if I go to www.stackoverflow.com/asdfasdf I get a 'Page Not Found' error but the URL still says www.stackoverflow.com/asdfasdf.

I would like to change the behavior so it matches how it works here in Stack Overflow, where I am shown the 404 page but the URL remains the same as I typed it. What would be the best way to do that? Thanks!

Try this:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM