Domain and subdomain routing in rails

02.19.2010

I needed to be able to route any domain that was not my own to a single controller.  And furthermore I had to route any subdomain that was not ” and not ‘www’ to that same controller.

If you can’t guess why, it is because it is a hosted application.  In any case, I used the request_routing plugin and it seemed OK for my needs.  The problem was, it didn’t accept things like :not => ‘www’ or :not => ”.  So, I ended up using a regular expression for my result.  Here goes.

  1.  not_domain_regex = Regexp.new(\A(?!(’ + AConfig::domain.gsub(‘.’, \.) + ‘))’, true)
  2.   is_domain_regex = Regexp.new(\A((’ + AConfig::domain.gsub(‘.’, \.) + ‘))’, true)
  3.   map.connect(
  4.     ‘*path’,
  5.     :controller => ‘external’,
  6.     :action => ‘handler’,
  7.     :conditions => {
  8.       :domain => not_domain_regex
  9.     }
  10.   )
  11.   map.connect(
  12.     ‘*path’,
  13.     :controller => ‘external’,
  14.     :action => ‘handler’,
  15.     :conditions => {
  16.       :domain  => is_domain_regex,
  17.       :subdomain => /([a-z0-9\-\_]{1,100}[^www])/i
  18.     }
  19.   )

The next step in this will be to replace “*path” with “:controller/:action/:id” and have it route to namespaced controllers.

Ex:

/controllers/external/controller_name.rb

If you have any ideas on that part.  Let me know :)

Leave a Reply

© Copyright 2009, JoshMattVander. Powered by Wordpress
Valid XHTML 1.0 Strict : Valid CSS 2