Skip to content

prepor/subdomain_routes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

75 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 subdomain routes which are keyed to a model (user, category, etc.) stored in your database.

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-subdomain_routes

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 changes ActionController::Resources::INHERITABLE_OPTIONS. 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.

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.

Defining Model-Based Subdomain Routes

The idea here is to have the subdomain of the URL keyed to an ActiveRecord model. Let’s take a hypothetical example of a site which lists items under different categories, each category being represented under its own subdomain. Assume our Category model has a subdomain attribute which contains the category’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 :model option:

ActionController::Routing::Routes.draw do |map|
  map.subdomain :model => :category do |category|
    category.resources :items
    ...
  end
end

As before, the namespace and name prefix for all the nested routes will default to the name of the model (you can override these in the options). The routes will match under any subdomain, and that subdomain will be passed to the controller in the params hash as params[:category_id]. For example, a GET request to dvds.example.com/items will go to the Category::ItemsController#index action with params[:category_id] set to "dvds".

Generating Model-Based Subdomain URLs

So how does URL generation work with these routes? That’s the best bit: just the same way as you’re used to! The routes are fully integrated with your named routes, as well as the form_for, redirect_to and polymorphic_path helpers. The only thing you have to do is make sure your model’s to_param returns the subdomain field for the user:

class Category < ActiveRecord::Base
  ...
  alias_method :to_param, :subdomain
  ...
end

Now, in the above example, let’s say our site has dvd and cd su categories, with subdomains dvds and cds. In our controller:

@dvd
=> #<Category id: 1, subdomain: "dvds", ... >

@cd
=> #<Category id: 2, subdomain: "cds", ... >

# when the current host is dvds.example.com:
category_items_path(@dvd)
=> "/items"

polymorphic_path [ @dvd, @dvd.items.first ]
=> "/items/2"

category_items_path(@cd)
=> "http://cds.example.com/items"

polymorphic_path [ @cd, @cd.items.first ]
=> "http://cds.example.com/items/10"

As you can see, the first argument for the named routes (and polymorphic paths) feeds directly into the subdomain for the URL. No more passing :subdomain options. Nice!

ActiveRecord Validations

SubdomainRoutes also gives you a couple of utility validations for your ActiveRecord models:

  • validates_subdomain_format_of ensures a subdomain field uses only legal characters in an allowed format; and
  • validates_subdomain_not_reserved ensures the field does not take a value already in use by your fixed-subdomain routes.

(Undoubtedly, you’ll want to throw in a validates_uniqueness_of as well.)

Let’s take an example of a site where each user gets a dedicated subdomain. Validations for the subdomain attribute of the User model would be:

class User < ActiveRecord::Base
  ...
  validates_subdomain_format_of :subdomain
  validates_subdomain_not_reserved :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 Fixed and Model-Based Subdomain Routes Together

Let’s try using fixed and model-based 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 :model => :user do |user|
    ...
  end
end

These routes will co-exist quite happily together. We’ve made sure our static subdomain routes are listed first though, so that they get matched first. In the User model we’d add the validations above, which in this case would prevent users from taking www or support as a subdomain. (We could also validate for a minimum and maximum length using validates_length_of.)

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 model-based subdomain routes (covered next), 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.

Copyright © 2009 Matthew Hollingworth. See LICENSE for details.

About

A Rails gem which adds subdomains to route recognition and generation.

Resources

License

Stars

Watchers

Forks

Packages

No packages published