Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A Rails gem which adds subdomains to route recognition and generation.
Ruby
Tag: v0.0.2

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.document
.gitignore
LICENSE
README.textile
Rakefile
VERSION.yml
subdomain_routes.gemspec

README.textile

SubdomainRoutes – Adding Subdomains to Rails Routing

The Rails routing system is a pretty impressive piece of code. There’s a fair bit of magic going on to make your routes so easy to define and use in the rest of your Rails application. One area in which the routing system is limited however is its use of subdomains: it’s pretty much assumed that your site will be using a single, fixed domain.

There are times where it is preferable to spread a website over multiple subdomains. One common idiom in URL schemes is to separate aspects of the site under different subdomains, representative of those aspect. It many cases a simple, fixed subdomain scheme is desirable: support.whatever.com, forums.whatever.com, gallery.whatever.com and so on. On some international sites, the subdomain is used to select the language and localization: en.wikipedia.org, fr.wikipedia.org, ja.wikipedia.org_. Other schemes allocate each user of the site their own subdomain, so as to personalise the experience (_blogspot.com is a good example of this).

A couple of plugins currently exists for Rails developers wishing to incorporate subdomains into their routes. The de facto standard is SubdomainFu. (I’ll admit – I haven’t actually used this plugin myself.) There’s also SubdomainAccount.

I’ve recently completed work on a subdomain library which fully incorporates subdomains into the rails routing environment – in URL generation, route recognition and in route definition, something I don’t believe is currently available. As an added bonus, if offers the ability to define routes for dynamic subdomains, which are recognised based on the contents of your database, or on other dynamic conditions.

Installation

The gem is called SubdomainRoutes, and is easy to install from GitHub (you only need to add GitHub as a source once):

gem sources -a http://gems.github.com
sudo gem install mholling-active_url

In your Rails app, make sure to specify the gem dependency in environment.rb:

config.gem "mholling-subdomain_routes", :lib => "subdomain_routes", :source => "http://gems.github.com"

(Note that the SubdomainRoutes gem requires Rails 2.2 or later to run since it uses ActiveSupport::Memoizable. If you’re on an older version of Rails, you need to get with the program. ;)

Finally, you’ll probably want to configure your session to work across all your subdomains. You can do this in your environment files:

# in environment/development.rb:
config.action_controller.session[:session_domain] = "yourdomain.local" # or whatever

# in environment/production.rb:
config.action_controller.session[:session_domain] = "yourdomain.com" # or whatever

Mapping a Single Subdomain

Let’s start with a simple example. Say we have a site which offers a support section, where users submit and view support tickets for problems they’re having. It’d be nice to have that under a separate subdomain, say support.mysite.com. With subdomain routes we’d map that as follows:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :support do |support|
    support.resources :tickets
    ...
  end
end

What does this achieve? A few things. For routes defined within the subdomain block:

  • named routes have a support_ prefix;
  • their controllers will have a Support:: namespace;
  • they will only be recognised if the host subdomain is support; and
  • paths and URLs generated for them by url_for and named routes will force the support subdomain if the current host subdomain is different.

This is just what you want for a subdomain-qualified route. Rails will recognize support.mysite.com/tickets, but not www.mysite.com/tickets.

Let’s take a look at the flip-side of route recognition – path and URL generation. The subdomain restrictions are also applied here:

# when the current host is support.mysite.com:
support_tickets_path
=> "/tickets"

# when the current host is www.mysite.com:
support_tickets_path
=> "http://support.mysite.com/tickets"

# overriding the subdomain won't work:
support_tickets_path(:subdomain => :www)
#  ActionController::RoutingError: Route failed to generate
#  (expected subdomain in ["support"], instead got subdomain "www")

Notice that, by necessity, requesting a path still results in an URL if the subdomain of the route is different. If you try and override the subdomain manually, you’ll get an error, because the resulting URL would be invalid and would not be recognized. This is a good thing – you don’t want to be linking to invalid URLs by mistake!

In other words, url_for and your named routes will never generate an invalid URL. This is one major benefit of the SubdomainRoutes gem: it offers a smart way of switching subdomains, requiring them to be specified manually only when absolutely necessary. (It gets even better with dynamic subdomains, which I will describe later.)

Mapping Multiple Subdomains

Subdomain routes can be set on multiple subdomains too. Let’s take another example. Say we have a review site, reviews.com, which has reviews of titles in several different media (say, DVDs, games, books and CDs). We want to key the media type to the URL subdomain, so the user knows by the URL what section of the site they’re in. (I use this scheme on my swapping site.) A subdomain route map for such a scheme could be as follows:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :dvd, :game, :book, :cd, :name => :media do |media|
    media.resources :reviews
    ...
  end
end

Notice that we’ve specified a generic name (media_) for our subdomain, so that our namespace and named route prefix become Media:: and media_, respectively. (We could also set the :name to nil, or override :namespace or :nameprefix individually.)

Recognition of these routes will work in the same way as before. The URL dvd.reviews.com/reviews will be recognised, as will game.reviews.com/reviews, and so on. No luck with concert.reviews.com/reviews, as that subdomain is not listed in the subdomain mapping.

URL generation may behave differently however. If the URL is being generated with current host www.reviews.com_, there is no way for Rails to know which of the subdomains to use, so you must specify it in the call to urlfor or the named route. On the other hand, if the current host is dvd.reviews.com the URL or path will just generate with the current host unless you explicitly override the subdomain. Check it:

# when the current host is dvd.reviews.com:
media_reviews_path
=> "/reviews"

# when the current host is www.reviews.com:
media_reviews_path
#  ActionController::RoutingError: Route failed to generate (expected
#  subdomain in ["dvd", "game", "book", "cd"], instead got subdomain "www")

media_reviews_path(:subdomain => :book)
=> "http://book.reviews.com/reviews"

Again, requesting a path may result in an URL or a path, depending on whether the subdomain of the current host needs to be changed. And again, the URL-writing system will not generate any URL that will not in turn be recognised by the app.

Mapping the Nil Subdomain

SubdomainRoutes allows you to specify routes for the “nil subdomain” – for example, URLs using example.com instead of www.example.com. To do this though, you’ll need to configure the gem.

By default, SubdomainRoutes just extracts the first part of the host as the subdomain, which is fine for most situations. But in the example above, example.com would have a subdomain of example; obviously, not what you want. You can change this behaviour by setting a configuration option (you can put this in an initializer file in your Rails app):

SubdomainRoutes::Config.domain_length = 2

With this set, the subdomain for example.com will be "", the empty string. (You can also use nil to specify this in your routes.)

If you’re on a country-code top-level domain (e.g. toswap.com.au), you’d set the domain length to three. You may even need to set it to four (e.g. for nested government and education domains such as health.act.gov.au).

(Note that, in your controllers, your request will now have a subdomain method which returns the subdomain extracted in this way.)

Here’s an example of how you might want to use a nil subdomain:

ActionController::Routing::Routes.draw do |map|
  map.subdomain nil, :www do |www|
    www.resource :home
    ...
  end
end

All the routes within the subdomain block will resolve under both www.example.com and just example.com.

(As an aside, this is not actually an approach I would recommend taking; you should probably not have the same content mirrored under two different URLs. Instead, set up your server to redirect to your preferred host, be it with the www or without.)

Finally, for the nil subdomain, there is some special behaviour. Specifically, the namespace and name prefix for the routes will default to the first non-nil subdomain (or to nothing if only the nil subdomain is specified). You can override this behaviour by passing a :name option.

Nested Resources under a Subdomain

REST is awesome. If you’re not using RESTful routes in your Rails apps, you should be. It offers a disciplined way to design your routes, and this flows through to the design of the rest of your app, encouraging you to capture pretty much all your application logic in models and leaving your controllers as generic and skinny as can be.

Subdomain routes work transparently with RESTful routes – any routes nested under a resource will inherit the subdomain conditions of that resource:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :admin do |admin|
    admin.resources :roles, :has_many => :users
    ...
  end
end

Your admin_role_users_path(@role) will automatically generate with the correct admin subdomain if required, and paths such as /roles/1/users will only be recognised when under the admin subdomain. Note that both the block form and the :has_many form of nested resources will work in this manner. (In fact, under the hood, the latter just falls through to the former.) Any other (non-resource) routes you nest under a resource will also inherit the subdomain conditions.

Setting Up Your Development Environment

To develop your app using SudomainRoutes, you’ll need to set up your machine to point some test domains to the server on your machine (i.e. to the local loopback address, 127.0.0.1). On a Mac, you can do this by editing /etc/hosts. Let’s say you want to use the subdomains www, dvd, game, book and cd, with a domain of reviews.local. Adding these lines to /etc/hosts will do the trick:

127.0.0.1 reviews.local
127.0.0.1 www.reviews.local
127.0.0.1 dvd.reviews.local
127.0.0.1 game.reviews.local
127.0.0.1 book.reviews.local
127.0.0.1 cd.reviews.local

You’ll need to flush your DNS cache for these changes to take effect:

dscacheutil -flushcache

Then fire up your script/server, point your browser to www.reviews.local:3000 and your app should be up and running. If you’re using Passenger to serve your apps in development (and I highly recommend that you do), you’ll need to add a Virtual Host to your Apache .conf file. (Don’t forget to alias all the subdomains and restart the server.)

If you’re using dynamic subdomain routes (covered in my next article), you may want to use a catch-all (wildcard) subdomain. Setting this up is not so easy, since wildcards (like *.reviews.local) won’t work in your /etc/hosts file. There are a couple of work-around for this:

  1. Use a proxy.pac file in your browser so that it proxies *.reviews.local to localhost. How to do this will depend on the browser you’re using.
  2. Set up a local DNS server with an A record for the domain. This may be a bit involved.

Dynamic Subdomain Recognition

SubdomainRoutes also offers a full complement of features for recognizing subdomain URLS which are not known in advance. (I’ll refer to these cases as dynamic subdomains.) For example, if you are keying each user of your website to their own subdomain, your routes will need to recognise new subdomains as new users sign up. Another example is if you want to key your URL subdomains to a set of categories (language, city, product type, etc.) which may expand as your site grows. In each case, your subdomains will depend on records in the database.

Let’s take a hypothetical example of a blogging site which lets users show and manage their blog under their own subdomains (think blogspot.com). Assume our User model has a subdomain attribute which contains the user’s custom subdomain. In our routes we’ll still use the subdomain mapper, but instead of specifying one or more subdomains, we just specify a :proc option:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :proc => :blog do |blog|
    blog.resources :articles, :has_many => :comments
    ...
  end
end

ActionController::Routing::Routes.recognize_subdomain :blog do |subdomain|
  User.exists?(:username => subdomain)
end

Note the last few lines, which are crucial. Here we are defining a method for recognizing blog subdomains. This is done using a new method, recognize_subdomain, which the gem adds to ActionController::Routing::Routes.

As arguments, the recognize_subdomain method takes a subdomain label, as used in the route (in this case, :blog), and a block. The block should take a single argument (the subdomain to be recognised), and should return true or false depending on whether the subdomain should be recognised for that route. In this case, we simply look up the subdomain in the User model to see if it’s in use.

That’s all there is to it! Now our blog routes will recognize more subdomains as more users sign up.

How does URL generation work with these routes? Pretty much as you’d expect. Let’s say our awesome new blogging site, awesomeblogs.com, has only two users, who’ve selected subdomains mholling and rails. In controllers and views, our named routes will work as follows:

# when the current host is mholling.awesomeblogs.com:
blog_articles_path
=> "/articles"

blog_articles_path(:subdomain => "rails")
=> "http://rails.awesomblogs.com/articles"

blog_articles_path(:subdomain => "www")
#  ActionController::RoutingError: Route failed to generate
#  (subdomain "www" is invalid)

# when the host is www.awesomeblogs.com:
blog_articles_path(:subdomain => "rails")
=> "http://rails.awesomblogs.com/articles"

blog_articles_path
#  ActionController::RoutingError: Route failed to generate
#  (subdomain "www" is invalid)

As you can see, the subdomain recognition method that we defined is being used to check for an invalid subdomain when the URL is being written. Nice!

Caching of Dynamic Subdomain Recognition

Internally, the results of the subdomain recognition block are cached. If this weren’t done, the block could be run many time per request (once for each route until one is recognised). That would be bad, since in most cases the database will be hit each time the block is called. (Sure, Rails will probably cache the database queries, but you may as well cache as high up the chain as you can.)

The problem then becomes – when does the cache get flushed? By default, this will occur once per request, which should be fine for many applications. If that’s the case, you don’t need to do anything.

To optimise performance however, you can disable the per-request cache flush and do it manually. Set this option in your configuration:

SubdomainRoutes::Config.manual_flush = true

In the above example we might want to choose this route, so that we can flush the cache only when a user is created or destroyed (or changes the subdomain). We could do this easily using an observer:

class UserObserver < ActiveRecord::Observer
  observe :user

  after_save(user)
    if user.subdomain_changed?
      ActionController::Routing::Routes.subdomain_procs.flush!
    end
  end

  after_destroy(user)
    ActionController::Routing::Routes.subdomain_procs.flush!
  end
end

# and in config/environment.rb:
config.active_record.observers = [ :user_observer ]

Another way to reduce the number of calls to the subdomain recognition block is by defining the dynamic subdomain route as late in routes.rb as possible. That way, the block will only be called if none of the other routes have resolved.

ActiveRecord Validations

SubdomainRoutes also gives you a utility validation, validates_subdomain_format_of, for your ActiveRecord models. If you’re storing a subdomain in a model (as we have been with our User example), you can use this validation to make sure that a subdomain field uses only legal characters and is in an allowed format. (Undoubtedly, you’ll want to throw in a validates_uniqueness_of as well.)

class User < ActiveRecord::Base
  ...
  validates_subdomain_format_of :subdomain
  validates_uniqueness_of :subdomain
  ...
end

The library currently uses a simple regexp to limit subdomains to lowercase alphanumeric characters and dashes (except on either end). If you want to conform more precisely to the URI specs, you can override the SubdomainRoutes.valid_subdomain? method and implement your own.

Using Static and Dynamic Subdomain Routes Together

Let’s try using static and dynamic subdomain routes together. Say we want to reserve some subdomains (say support and admin) for administrative functions, with the remainder keyed to user accounts. Our routes:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :support do |support|
    ...
  end
  map.subdomain :admin do |admin|
    ...
  end
  map.subdomain :proc => :user do |user|
    ...
  end
end

ActionController::Routing::Routes.recognize_subdomain :blog do |subdomain|
  User.exists?(:username => subdomain)
end

These routes will co-exist quite happily together. (We’ve made sure our static subdomain routes are listed first though.) In the User model we’ll add an extra validation to prevent users from taking the reserved subdomains:

validates_exclusion_of :subdomain, :in => %w{support admin www}

(We could also validate for a minimum and maximum length.)

Copyright © 2009 Matthew Hollingworth. See LICENSE for details.

Something went wrong with that request. Please try again.