TRAFEX TRAFEX Consultancy Consultancy
Caching WordPress with Nginx

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.

Configuration

I’ve created the following configuration.

The 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. The wordpress-website.conf must be placed in the sites-available folder and a symlink must exist to this file from the sites-enabled folder.

Caching strategy

The caching strategy is simple; Try to cache every call to PHP-FPM for one week. There are a few exceptions to this rule ( see the $skip_cache variable in wordpress-website.conf):

  1. POST requests
  2. Requests with a query string
  3. Requests to:
  • /wp-admin
  • /xmlrpc.php
  • /wp-*.php
  • /feed
  • index.php
  • sitemap*.xml
  1. Request with one of the following cookies:
  • comment_author
  • wordpress_*
  • wp-postpass
  • wordpress_no_cache
  • wordpress_logged_in

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).

Go back

Related content

Projects

WordPress Docker image

A lightweight and up-to-date WordPress docker image with PHP8 and Nginx.

Read More