Setting up multiple asset hosts in Rails
published Oct 24, 2007
NOTE: The svn repository referenced here is no longer running. Hopefully you’re running an new enough version of Rails that this post isn’t necessary.
One of the nice goodies coming in Rails 2.0 is the ability to use multiple asset hosts. This article explains how you can use this feature now, without waiting for Rails 2.0, and why you would want to use asset hosts.
What’s an asset host, and why would I want to use it?
So, why would you want to use an asset host? It turns out that many browsers limit the number of simultaneous connections to a host. For Internet Explorer, that number is two. If you are serving a lot of small images, or you haven’t bothered to bundle your scripts or stylesheets, this can be a real bottleneck. Asset hosting allows you to increase the number of hosts a web page is loaded from, removing the bottleneck.
Asset hosting in Rails
Rails has had support for using a single asset host for at least a year. It’s achieved by setting
config.action_controller.asset_host in your development environment,
development.rb. For example,
Once you do this, rails will pre-pend every link created with an asset tag helper with your asset host name. So, a link like this
will now result in the following link
Asset tag helpers are things like
Multiple asset hosts
Now, having a single asset host is nice, but using multiple asset hosts can really speed up those page load times. Here’s how you do it:
Get Rails ready for multiple asset hosts
There are two ways you can do this.
Upgrade to Rails 2.0
For instructions, scroll to the bottom of this post.
Install the multiple_asset_hosts plugin
script/plugin install svn://svn.spattendesign.com/svn/plugins/multiple_asset_hosts
All this plugin does is monkeypatch in the multiple asset host functionality from Rails Edge.
Pick a name for your asset hosts
The change from single to multiple asset hosts is simple. You simply put a
%d somewhere in your asset host name in
production.rb. For Plot-O-Matic, the setting is
Rails will replace the
%d with either 0, 1, 2 or 3.
Set up your asset hosts
You need to provide four asset hosts, so I set up four asset hosts named
I used Amazon S3 for my asset hosts, which was simple:
- set up four buckets called
- Set up a CNAME entry for each asset host pointing to
s3.amazonaws.com. How you do this depends on your domain host. Here’s what it looks like on easydns
- Commit your changes to your version control system
- Upload everything in your public directory to each of your asset hosts.
- Deploy and restart your web server