Performance Tuning Wordpress: Far-Future Headers and Cache Busting
A number of caching plugins exist for Wordpress, but they all seemed a little more complex than I needed. Plus I like to rely as little on 3rd party code as I can. So here’s a simple solution using a single php function and .htaccess file.
First, Enable Caching
To set up caching in Apache you just add a few mod_expires directives to your .htaccess file. First, if you don’t already have one, create a text file, name it .htaccess (notice the leading dot), and save it in the root of your Wordpress installation (make sure you save this in the root of your Wordpress installation, not your theme folder). Add the following lines.
Second, Bust the Cache
In a nutshell here’s what’s happening. The function…
1. Takes the URL to a file and converts it to a local file path,
2. Checks when the file was last modified and
3. Adds a timestamp right before the file extension.
So, for example, if you pass this URL to the function
http://example.com/styles/styles.css, and that file was last changed on Oct 1st 2013 at 10:00 am, the function will return
To use this function just add it to your header.php (and any other template files that reference assets). For example.
Wordpress Template File
Notice in line 8, we wrap the call to
get_bloginfo('stylesheet_url') in our
cache_buster_url function. The stylesheet URL returned by
get_bloginfo() gets a timestamp added to it. If the get_bloginfo function looks foreign to you, check out the Wordpress documentation.
Third, Avoid “File Not Found”
Now that we’ve handled dynamically versioning our asset file names, we have to handle the process in the opposite direction. There is no file named
http://example.com/styles/styles.20131001100000.css, so when the request comes in to the web server, we’re going to get a 404 file not found error. What we have to do is make sure that requests for these timestamped URLs get translated back to the real, non-timestamped file name. Luckily, if you’re using Apache, this is easy to do with a few lines added to your .htaccess file.
The Apache module mod_rewrite can take an incoming url and rewrite it before passing it on. With a few lines we can take any request for our assets that contains a timestamp and strip the timestamps out leaving the original, “real” file name. Add this to your .htaccess file…
To understand the full syntax, see the mod_rewrite documentation. What is of interest to us here are lines 11-13. Lines 11 and 12 make sure that there is not a real file or directory (respectively) matching the request. If not, line 13 rewrites any request for a JS, CSS, PNG, JPG or GIF file, stripping out the timestamp. Now
http://example.com/styles/styles.20131001100000.css changes back to
So this is kind of a long explanation. Let’s quickly recap what’s going on.
- We use the php function
- We configure our web server to rewrite incoming requests for assets, stripping out the timestamps.