Host and domain based routing in Ruby on Rails

Published 20 January 2010

I spent some time trying to figure out how to have host-based routing in our upcoming Ruby on Rails application.\r\n\r\nThe Ruby Gem subdomain-fu almost gave me what I wanted, except it only allowed routing based on sub-domain rather than the entire host name in the URL.\r\n\r\nThe purpose is to allow our clients to have any domain point to our server, and correctly determine what to render based on a database match of the domain.\r\n\r\nTo achieve this I forked subdomain-fu, and simply added 2 lines to routing_extensions.rb:\r\n\r\n@@@ ruby\r\n def recognition_conditions_with_subdomain\r\n result = recognition_conditions_without_subdomain\r\n result << \“conditions[:subdomain] === env[:subdomain]\” if conditions[:subdomain] && conditions[:subdomain] != true && conditions[:subdomain] != false\r\n result << \“SubdomainFu.has_subdomain?(env[:subdomain])\” if conditions[:subdomain] == true\r\n result << \“!SubdomainFu.has_subdomain?(env[:subdomain])\” if conditions[:subdomain] == false\r\n\r\n # added these 2 lines:\r\n result << \“conditions[:domain] === env[:domain]\” if conditions[:domain]\r\n result << \“conditions[:host] === env[:host]\” if conditions[:host]\r\n result\r\n end\r\n@@@\r\n\r\nI’m not clear why these weren’t added in the subdomain-fu gem, since the detection of domain and host are already stored in the env array.\r\n\r\nThen modify the routes.rb file to include the new conditions:\r\n\r\n@@@ ruby\r\nActionController::Routing::Routes.draw do |map|\r\n\r\n map.connect \“\”, :controller => \“home\”, :conditions => { :host => \“\” }\r\n map.connect \“\”, :controller => \“listings\”\r\n \r\n map.connect ‘:controller/:action/:id’\r\n map.connect ‘:controller/:action/:id.:format’\r\nend\r\n@@@\r\n\r\nAs the routes are checked sequentially for a match, if isn’t matched then we fall through to the second map.connect entry which is a catch all for any other domain.\r\n\r\nThe difference between host and domain is the domain is the part after the subdomain (e.g., whereas the host is the subdomain and domain (e.g.\r\n\r\n\See the original subdomain-fu gem for more details\\My forked gem is available on Github\ Railscasts has a \useful vid on the topic\