views:

29

answers:

2

I've got a simple Rails application running as a splash page for a website that's going through a transition to a new server. Since this is an established website, I'm seeing user requests hitting pages that don't exist in the Rails application.

How can I redirect all unknown requests to the homepage instead of throwing a routing error?

A: 

You can use the following ways to handle errors in a common place. Place this code in you ApplicationController

  def rescue_404
    @message = "Page not Found"
    render :template => "shared/error", :layout => "standard", :status => "404"
  end

  def rescue_action_in_public(exception)
    case exception
      when CustomNotFoundError, ::ActionController::UnknownAction then
        #render_with_layout "shared/error404", 404, "standard"
        render :template => "shared/error404", :layout => "standard", :status => "404"
      else
        @message = exception
        render :template => "shared/error", :layout => "standard", :status => "500"
    end
  end

Modify it to suit your needs, you can have redirects as well.

HTH

Rishav Rastogi
This is probably more useful if there were only a couple places that people were going, but unfortunately I can't predict all the links people are coming from. Thanks for your help though. You might find the routes-based solution posted here interesting as well!
Dean Putney
+2  A: 

I just used route globbing to achieve this:

map.connect "/*other", :controller => "pages", :action => "index"

Note that this route should be at the end of routes.rb so that all other routes are matched before it.

Alex - Aotea Studios
Solved my problem quickly, perfectly and elegantly. Thanks for your help!
Dean Putney