Static Content with Far-Future Expires Headers

If you have not read Yahoo!’s Best Practices for Speeding Up Your Website, you should definitely go through that now. It cover’s a lot of information that every web developer / web server admin should know. Once you have read through that document, you can use the Firefox YSlow extension to examine your website and let you know how well it follows Yahoo!’s rules.

One issue that I ran into while implementing these rules was an efficient and effective way to add far-future expiration headers to my static content. My first attempt had entries in the web server configuration file for every directory that I wanted these headers on. While this did work, any change I wanted to make required editing the server configuration and restarting the server daemon. Also, not everybody has access to the server configuration files.

A popular option is to use .htaccess files in folders you want to add headers for. This wasn’t an option for me since I’m using Lighttpd and not Apache. Also, if your goal is performance then you should not be using them anyway.

The solution that I came up with was to create a subdomain (static.thewaffleshop.net). This subdomain has the same document root as the regular domain. The only thing it does differently is add far-future expiration tags to any content accessed through the subdomain. Using lighttpd conditionals, this was extremely easy to configure:

$HTTP["host"] =~ "^static\." {
        expire.url = ( "" => "access 1 years" )
}
$HTTP["host"] =~ "^(www\.|static\.)?thewaffleshop\.net$" { ... }
$HTTP["host"] =~ "^(static\.)?thewaffleshop\.net$" { ... }

There is one conditional to see if the host starts with static., and the other vhost configurations only need slightly modified to pass through the static subdomain. I’m not sure how you would do this in Apache, perhaps using ServerAlias? Apache guru’s please leave a comment if you know how to implement this.

This solution is incredibly flexible – adding and removing expiration headers is as simple as changing the URL for the files. Just make sure that you never link to content via the static subdomain – different URL’s to the same content is a big SEO (Search Engine Optimization) no-no.

Leave a Comment