Caching WordPress with Nginx

Wordpress caching configuration

I’m running this blog 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 due to 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 a few exceptions on 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
  4. 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).


Comments

  1. Chirag Swadiahirag
    June 3, 2014 - 3:57 pm

    Lets automate this using EasyEngine

    EasyEngine can easily setup 12 different type wordpress including wordpress multisite and different caching support

    Read More: https://github.com/rtCamp/easyengine

  2. avadhootkulkarni
    June 24, 2014 - 12:34 pm

    @Chirag I second you. EasyEngine works like magic and really easy to setup.
    https://rtcamp.com/easyengine

  3. True, EasyEngine makes this very ‘Easy’ šŸ™‚ But I like to be in control. This is a simple and straightforward configuration that doesn’t need any external tools and is easy to modify if it doesn’t exactly fits your needs.

Leave a Reply