Tuesday, October 6, 2009

Rails Routes according to the Domain

Routing using Rails is quite simple, you define routes and where they point at. The order in which routes are declared defines their priority. Very simple.

Now Rails also provides conditions on routes according to the HTTP method used, and using the request_routing plugin we can use more conditions. We specially use it for the domain, or sub domain used for example. The Frontfoot website and the Frontfoot mobile site are the same rails application, they just use different routing according to the domain used.

map.connect '/:action',  :controller => 'mobile',
                         :conditions => { :domain => /\.mobi/i }
map.connect '/:action',  :controller => 'main'

That works well if the domain has only one TLD like frontfoot.mobi, but if the domain has two TLDs it doesn't work. In this case we do the test on frontfoot.mobi so it works well.

Now what if we have two domains like for example frontfoot.com.au and ffmobile.com.au. Well that doesn't work. The :domain option will test the domain against 'com.au' we could then use sub-domain to get 'frontfoot' but in that case if we use 'www' it won't work because the :subdomain option tests only the first sub-domain.

So here is the solution! I have written a fork of the plugin to add a :domain_2 option which just gets the domain considering it has 2 TLDs. And there you go you can write:

map.connect '/:action',  :controller => 'mobile',
                         :conditions => { :domain_2 => /ffmobile\.com\.au/i }
map.connect '/:action',  :controller => 'main'

Enjoy! It's tested and on my github. :)

1 comment: