NGINX + WP Super Cache = Awesome

WP Super Cache is one of the simple WordPress caching plugins available. It’s free, it’s fast, and it’s great.

The problem

WP Super Cache can serve cached pages with either PHP, or some .htaccess rules. While this is great if you’re on Apache and have .htaccess enabled, it creates a problem for those of us on NGINX, or even Lighttpd. As NGINX has no support for .htaccess, you’re stuck with using PHP to serve files. This will work, but you can serve pages even faster by bypassing PHP, and using NGINX directly. Sounds simple, right? All you need is to modify your virtual host according to the codex, and you’re done. However, it requires editing the location block, which makes things considerable more difficult than W3 Total Cache, where all you need to do is add include /var/www/wpdir/nginx.conf and be done.

The solution

While you can modify the rules a bit and put them in nginx.conf like W3 Total Cache, NGINX will refuse to restart because there are two location / blocks. This isn’t NGINX’s fault, as if there are two of the same location blocks, which one gets used? I spent some time looking at how W3 Total Cache does it, combining it with the rules found on the Codex, and coming up with two nginx.conf files: one without mobile support, and one with. All you need is to put the rules in a file, and include it from the virtual host.

Why are there two versions?

One version has mobile support, and one just uses the main cache file($uri/index.html) for everything. Technically, the mobile version could work even without the setting enabled, but it would be slower. The reason is that NGINX will check if it’s a mobile device, and if it is, serve a different cache file. Well, without the setting in WP Super Cache enabled, that mobile cache file will not exist. The rewrite to the cached version will not occur, and all mobile requests will go to PHP. Mobile themes will work fine, but mobile devices won’t get the performance boost cached files add.

Why not just use the PHP option?

If your site loads fine with the PHP mode, you’re probably wondering if you should make the switch to using NGINX directly. Here are some reasons aside from speed that makes the configuration worthwhile:

  • Your site will be up if the database crashes: If the page is already cached, users that are not logged in will still be able to access your site instead of getting a database error.
  • Your site will be up if PHP crashes: Same reason as the database
  • Traffic spikes will not break your server: If your site works fine with low traffic, what happens if you do get a traffic spike? If you use PHP mode, your server will be able to handle more users, but not nearly as much as directly with NGINX. Do you really want to risk serving a timeout error during a traffic spike instead of spending two minutes configuring NGINX?