Thunder Data Systems

Catch-all Routes in Rails

Catch-all Routes in Rails

On one of our projects we were porting over a legacy application written in PHP to Rails. A lot of the application’s users accessed the site with bookmarked pages. So we wanted to redirect users when we saw specific words like “buy” or “.php”, so customers were not left staring at a 404 page.

To accomplish this we simply added a “catch-all” route in Rails. This allowed us to inspect the path and take action based on some kind of business logic. Below is the code added to the end of the routes.rb file:

map.connect ‘*path’, :controller => ‘redirect’, :action => ‘index’

This will redirect any requests that are not matched in the routes files to the redirect controller’s index action. In that method we can then define logic on how we want to handle the request. We can even perform actions with the database, since we’re inside a controller at this stage. In our case we simply used a regular expression to evaluate the URI:

def index if request.request_uri =~ /buy|.php/ redirect_to “/” else render :file => “#{RAILS_ROOT}/public/404.html”, :status => 404 end end

It’s a simple, yet powerful little technique for handling URLs dynamically.

Leave a Reply

Your email address will not be published.