Nginx + Wordpress caching that actually works

by Martin Westin in ,


I spent a lot of time yesterday trying to enable WP Super Cache, and subsequently W3 Total Cache for this website. SInce none of the hits I got on Google did the trick I thought I'd post my working settings for page caching with W3 Total Cache. I went with this plugin mainly because it uses a logical hierarchy of readable folders and files. WP Super Cache did not which is why I eventually dropped it and tried the Total Cache plugin.

I have Nginx and PHP FastCGI. No Apache. The "problem" with this setup is the rewrite rules needed to point visitors to cached pages if they exist. Installing the plugin is as simple as anything in WP these days so I wont go into that.

Here it is:

## W3 Total CACHE BEGIN
set $totalcache_file '';
set $totalcache_uri $request_uri;

if ($request_method = POST) {
  set $totalcache_uri '';
}

# Using pretty permalinks, so bypass the cache for any query string
if ($query_string) {
  set $totalcache_uri '';
}

if ($http_cookie ~* "comment_author_|wordpress|wp-postpass_" ) {
  set $totalcache_uri '';
}

# if we haven't bypassed the cache, specify our totalcache file
if ($totalcache_uri ~ ^(.+)$) {
  set $totalcache_file /wp-content/w3tc/pgcache/$1/_index.html;
}

# only rewrite to the totalcache file if it actually exists
if (-f $document_root$totalcache_file) {
  rewrite ^(.*)$ $totalcache_file;
  break;
}                 

##W3 Total CACHE END

If you are wondering what to do with these lined of code... I did not come up with them myself. I did a minor change to make them work with the current version of WP Total Cache and my installation.

The blueprint came from here: http://wpveda.com/nginx-rewrite-rules-for-w3-total-cache-plugin/

What I did was to change the filename. Also. If you, like me, have wp in a folder you would add that to the path as well.

set $totalcache_file /wp-content/w3tc/pgcache/$1/_index.html;
set $totalcache_file /your-wp-folder/wp-content/w3tc/pgcache/$1/_index.html;

There are a dozen other sites with variations on this code. None worked for me straight away... If you have similar experience, maybe my version will work for you.

When, or if, I get some of the other rewrite-dependent features working I'll add another post.