We’ve previously mentioned the asset host setup we created for La Cucina Italiana. For the most recent revision, which includes user registration, we had to add another layer to the mix: SSL.
The standard operating procedure for Rails applications and SSL is to create the SSL host (which functions, in Apache, as another virtual host) and proxy it directly to the same Ruby httpd you’re using to run the rest of the site, with the added request header to indicate that yes, this one came in via SSL.
The problem is that Rails then generates a page in which all the sub-requests use SSL. This is a problem when you’re using asset hosts, unless you’ve either paid extra for a certificate that covers your asset host subdomains (and why this should cost extra is beyond me, by the way, but nearly nobody does it) or are willing to force Rails to not securely link page assets, which leads to “mixed content” warnings from many browsers (a secure page including insecure components.)
The solution to this problem is in the Rails documentation where the asset hosts are described in the first place: you generate the asset hosts using a proc. There are two gotchas here, though: First, you need to be using Rails 2.1.0 or better. (This, combined with the Ruby problems that came up last month, pushed La Cucina to Rails 2.1.) The example in the documentation, however, only allows for one asset host, and the %d solution for randomizing across four hosts doesn’t work within a proc. Here’s how to manage it, if you weren’t able to figure that out from the documentation:
ActionController::Base.asset_host = Proc.new { |source, request|
if request.ssl?
"#{request.protocol}#{request.host_with_port}"
else
"#{request.protocol}a#{rand(4)}.lacucinaitalianamagazine.com"
end
}
Essentially, this turns off asset hosting for requests using SSL, which means those requests will come through the application itself. Fortunately for us, all the SSL-requiring pages don’t use content which isn’t under source control!

It’s best to use an id generated from the hash of the source URL rather than a random digit, e.g.
“media%d.homeflow.co.uk” % (source.hash % 4)
So that the same source always ends up on the same asset server and doesn’t defeat downstream caching.
Andy – that’s a nice idea, keeping each asset (script, stylesheet, image) on one virtual asset server. Thanks for sharing.