Custom 404 Routes & Pages in Rails

November 3rd, 2007

Lately, I’ve been using a nice ‘catch-all’ trick in my routes.rb file to send users to a custom 404 page. It’s as simple as throwing this below the rest of your routes:

1
2
3
4
5
# If the user has typed an Invalid URL
map.connect "*path", :controller => "www", :action => "unrecognized"

# Make sure you don't have this default route in there:
# map.connect ':controller/:action/:id' # Comment or remove!

Now, if any invalid URLs are typed in, the app will respond by dishing up the action ‘unrecognized’ from the WwwController.

Here’s where the problem comes in. We recently redesigned a site using Rails, however I noticed that Google was continuing to index the old PHP version of the site just as it always had. Instead of removing the page from it’s index, it was displaying the content of my new custom 404 page. After some research, I realized the reason was my custom 404 page wasn’t a true 404, and was instead sending a 200 Successful HTTP response header instead. This turned out to be a quick fix, but I found it quite undocumented on the net:

1
2
3
4
5
class WwwController < ApplicationController
  def unrecognized
    render( :status => "404 Not Found" )
  end
end

Now our server will dish up the standard ‘404 Not Found’ HTTP response header. It’s just that easy.

Sorry, comments are closed for this article.