Caching WordPress with Nginx
June 2, 2014
I’m running a WordPress website on a small VPS with the help of Nginx and PHP-FPM. But I noticed the site was not that fast as I wanted it to be. This is mainly caused by the little resources this VPS has. So every request needs to be as efficient as possible. To make that possible, I want to cache the requests with Nginx to minimize the requests that needs to be handled by PHP-FPM.
I’ve created the following configuration.
caching.conf file must be placed in the
conf.d folder. This defines
the cache path for the
WORDPRESS zone, the cache_key, and how Nginx should handle when upstream returns an error.
wordpress-website.conf must be placed in the
sites-available folder and a symlink must exist to this file from
The caching strategy is simple; Try to cache every call to PHP-FPM for one week. There are a few exceptions to this rule (
$skip_cache variable in
- POST requests
- Requests with a query string
- Requests to:
- Request with one of the following cookies:
These exceptions make sure you’ll never get a cached page when you’re logged in or just posted a comment.
Purging the cache
The downside of this simple but effective strategy is that there isn’t a way to automatically purge the cache when you add or change something on your website. There are modules for Nginx to purge the cache and plugins for Wordpress to do this when needed. But, I don’t need that. I’ll just remove the cache manually:
$ sudo rm -rf /var/run/nginx-cache/*
See the result
Make sure you’re not logged in to test how superfast your website is! Every page includes a
X-Cache header which
tells you whether a page is served from cache (hit) or not (miss).