Enable a WordPress Full-Page Cache with NGINX fastcgi_cache (PHP-FPM, Purge on Update)

On this page9 sections

This post shows how to add a full-page cache to WordPress with NGINX fastcgi_cache on Ubuntu 24.04: repeat page views are served without PHP, logged-in users and forms bypass it, and a small plugin empties it when content changes.

Lab context

  • Web server
    • OS: Ubuntu 24.04
    • NGINX: 1.24.0, PHP-FPM: 8.3.6
    • WordPress: 7.1.5, theme Astra, Polylang (language in the URL)

What you’ll build

  • maksonlee-page-cache.conf: the cache zone and the bypass rules
  • Cache settings in the site’s PHP location, plus an X-Cache header
  • Maksonlee Page Cache Purge: a plugin that empties the cache when content changes

Prerequisites

  • WordPress on NGINX + PHP-FPM (here /etc/nginx/sites-available/maksonlee)
  • PHP-FPM runs as www-data, the same user as NGINX
  • curl and the PHP CLI on the server, and an administrator account

NGINX doesn’t cache a response that sets a cookie, and Polylang sets pll_language on every page. With the language in the URL (and browser-language detection off), the cookie isn’t needed. Add PLL_COOKIE to wp-config.php:

sudo sed -i "1a define( 'PLL_COOKIE', false );" /var/www/html/maksonlee/wp-config.php
sudo grep -n PLL_COOKIE /var/www/html/maksonlee/wp-config.php

Expected:

2:define( 'PLL_COOKIE', false );

Reload PHP-FPM:

sudo systemctl reload php8.3-fpm

2. Create the cache zone and bypass rules

Create /etc/nginx/conf.d/maksonlee-page-cache.conf:

# Full-page cache for www.maksonlee.com (WordPress), used by sites-available/maksonlee.
# The maksonlee-page-cache plugin empties it when content changes.
fastcgi_cache_path /var/cache/nginx/maksonlee levels=1:2 keys_zone=maksonlee_pages:32m max_size=1g inactive=7d use_temp_path=off;

# Each map is 1 when the request must neither use nor fill the cache.
map $http_cookie $maksonlee_nocache_cookie {
    default 0;
    "~*(wordpress_logged_in_|wordpress_sec_|wp-postpass_|comment_author_|wordpress_no_cache)" 1;
}

map $request_uri $maksonlee_nocache_uri {
    default 0;
    "~\?" 1;
    "~^/(wp-admin|wp-login\.php|wp-json|wp-cron\.php|wp-comments-post\.php|wp-signup\.php|wp-activate\.php|wp-trackback\.php|xmlrpc\.php|index\.php)" 1;
    "~(^|/)feed/?$" 1;
    "~sitemap[^/]*\.xml$" 1;
    # WPForms pages (contact, zh-CN, zh-TW): the form carries per-request values
    "~*^/(zhtw/|zhcn/)?(contact|%e8%81%94%e7%b3%bb%e6%88%91|%e8%81%af%e7%b5%a1%e6%88%91|联系我|聯絡我)/?$" 1;
}

map $request_method $maksonlee_nocache_method {
    default 1;
    GET 0;
    HEAD 0;
}

# Phone and desktop pages differ (Astra adds ast-header-break-point when wp_is_mobile()), so they are cached
# separately. Same rules as WordPress's wp_is_mobile(): the Sec-CH-UA-Mobile hint first, then the user agent.
map $http_user_agent $maksonlee_ua_device {
    default d;
    "~(Mobile|Android|Silk/|Kindle|BlackBerry|Opera Mini|Opera Mobi)" m;
}
map $http_sec_ch_ua_mobile $maksonlee_device {
    default d;
    "" $maksonlee_ua_device;
    "?1" m;
}
  • Bypass: logged-in users, commenters, query strings, wp-admin, login, REST API, feeds, sitemaps, and the contact form pages (use your own form URLs).
  • Phones: Astra sends phones different HTML, so they get their own copy.

3. Enable the cache in the PHP location

Edit /etc/nginx/sites-available/maksonlee. Add at the end of location ~ \.php$ { … }:

        fastcgi_cache maksonlee_pages;
        fastcgi_cache_key "$scheme$request_method$host$request_uri$maksonlee_device";
        fastcgi_cache_valid 200 301 10h;
        fastcgi_cache_bypass $maksonlee_nocache_cookie $maksonlee_nocache_uri $maksonlee_nocache_method $http_authorization;
        fastcgi_no_cache $maksonlee_nocache_cookie $maksonlee_nocache_uri $maksonlee_nocache_method $http_authorization;
        fastcgi_cache_lock on;
        fastcgi_cache_lock_timeout 10s;
        fastcgi_cache_use_stale updating error timeout;
        fastcgi_cache_background_update on;

Only 200 and 301 responses are cached, for 10 hours, so nonces in cached pages (e.g., Akismet’s in the comment form, valid for at least 12 hours) still work.

Add next to the other add_header lines, in the server block (not in a location, or PHP pages lose the other headers):

    add_header X-Cache $upstream_cache_status always;

4. Create the cache directory and reload NGINX

Ubuntu’s NGINX package has no /var/cache/nginx:

sudo install -d -m 0755 /var/cache/nginx
sudo nginx -t
sudo systemctl reload nginx

Expected:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

5. Install the purge plugin

Create the plugin directory:

sudo mkdir -p /var/www/html/maksonlee/wp-content/plugins/maksonlee-page-cache

Create /var/www/html/maksonlee/wp-content/plugins/maksonlee-page-cache/maksonlee-page-cache.php:

<?php
/**
 * Plugin Name: Maksonlee Page Cache Purge
 * Description: Empties the nginx full-page cache (fastcgi_cache) when published content, comments, menus, widgets, settings or plugins change. Adds `wp maksonlee-cache purge`.
 * Version: 1.0.1
 * Author: Makson Lee
 * Requires PHP: 8.1
 */

defined( 'ABSPATH' ) || exit;

if ( ! defined( 'MAKSONLEE_PAGE_CACHE_DIR' ) ) {
	define( 'MAKSONLEE_PAGE_CACHE_DIR', '/var/cache/nginx/maksonlee' );
}

final class Maksonlee_Page_Cache {
	private static bool $pending = false;

	public static function init(): void {
		add_action( 'transition_post_status', array( __CLASS__, 'on_post_transition' ), 10, 3 );
		add_action( 'before_delete_post', array( __CLASS__, 'on_post_delete' ), 10, 2 );
		add_action( 'transition_comment_status', array( __CLASS__, 'schedule' ), 10, 0 );
		add_action( 'comment_post', array( __CLASS__, 'on_comment_post' ), 10, 2 );
		add_action( 'edit_comment', array( __CLASS__, 'on_comment_edit' ), 10, 1 );
		foreach ( array( 'created_term', 'edited_term', 'delete_term', 'wp_update_nav_menu', 'wp_update_nav_menu_item', 'wp_delete_nav_menu', 'switch_theme',
			'customize_save_after', 'activated_plugin', 'deactivated_plugin', 'upgrader_process_complete' ) as $hook ) {
			add_action( $hook, array( __CLASS__, 'schedule' ), 10, 0 );
		}
		add_action( 'updated_option', array( __CLASS__, 'on_option' ), 10, 1 );
		add_action( 'shutdown', array( __CLASS__, 'flush' ), 99, 0 );
	}

	/** Not public, but shown on every page: menus, block navigation, templates, synced patterns, global styles. */
	private const LAYOUT_TYPES = array( 'nav_menu_item', 'wp_navigation', 'wp_template', 'wp_template_part', 'wp_block', 'wp_global_styles' );

	public static function on_post_transition( string $new, string $old, WP_Post $post ): void {
		if ( in_array( $post->post_type, self::LAYOUT_TYPES, true ) ) {
			self::schedule();
			return;
		}
		if ( 'publish' !== $new && 'publish' !== $old ) {
			return;
		}
		if ( wp_is_post_revision( $post ) || wp_is_post_autosave( $post ) ) {
			return;
		}
		$type = get_post_type_object( $post->post_type );
		if ( $type && $type->public ) {
			self::schedule();
		}
	}

	public static function on_post_delete( int $post_id, WP_Post $post ): void {
		self::on_post_transition( 'deleted', $post->post_status, $post );
	}

	public static function on_comment_post( int $comment_id, $approved ): void {
		if ( 1 === $approved || '1' === $approved ) {
			self::schedule();
		}
	}

	public static function on_comment_edit( int $comment_id ): void {
		if ( 'approved' === wp_get_comment_status( $comment_id ) ) {
			self::schedule();
		}
	}

	public static function on_option( string $name ): void {
		if ( preg_match( '/^(widget_|theme_mods_|sidebars_widgets$|blogname$|blogdescription$|permalink_structure$|show_on_front$|page_on_front$|page_for_posts$|posts_per_page$|polylang$|wpseo|site_icon$|date_format$|time_format$)/', $name ) ) {
			self::schedule();
		}
	}

	public static function schedule(): void {
		self::$pending = true;
	}

	public static function flush(): void {
		if ( self::$pending ) {
			self::$pending = false;
			self::purge();
		}
	}

	/** Deletes every cached file under MAKSONLEE_PAGE_CACHE_DIR; refuses any directory outside /var/cache/nginx/. */
	public static function purge(): array {
		$dir = realpath( MAKSONLEE_PAGE_CACHE_DIR );
		if ( false === $dir || ! is_dir( $dir ) || 0 !== strpos( $dir . '/', '/var/cache/nginx/' ) || '/var/cache/nginx' === $dir ) {
			return array( 'deleted' => 0, 'failed' => 0, 'error' => 'cache directory missing or not under /var/cache/nginx/' );
		}
		$deleted = 0;
		$failed  = 0;
		$items   = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS ),
			RecursiveIteratorIterator::CHILD_FIRST
		);
		foreach ( $items as $item ) {
			if ( $item->isFile() && ! $item->isLink() ) {
				if ( @unlink( $item->getPathname() ) ) {
					++$deleted;
				} else {
					++$failed;
				}
			}
		}
		return array( 'deleted' => $deleted, 'failed' => $failed );
	}
}

Maksonlee_Page_Cache::init();

if ( defined( 'WP_CLI' ) && WP_CLI ) {
	WP_CLI::add_command(
		'maksonlee-cache purge',
		static function () {
			WP_CLI::success( wp_json_encode( Maksonlee_Page_Cache::purge() ) );
		}
	);
}

Set the owner and check the syntax:

sudo chown -R www-data:www-data /var/www/html/maksonlee/wp-content/plugins/maksonlee-page-cache
sudo php -l /var/www/html/maksonlee/wp-content/plugins/maksonlee-page-cache/maksonlee-page-cache.php

Expected:

No syntax errors detected in /var/www/html/maksonlee/wp-content/plugins/maksonlee-page-cache/maksonlee-page-cache.php

Activate it:

  • Plugins → Installed Plugins → Inactive → Maksonlee Page Cache Purge → Activate
The inactive Maksonlee Page Cache Purge plugin with its Activate link

We empty the whole cache: every page in every language, phone and desktop copies alike. A post also shows up on the home page, in archives, and in recent-post lists, so clearing everything is safer than tracking each page.

  • Empties the cache:
    • publishing, updating, unpublishing, or deleting a published post or page
    • a new or edited approved comment, or any comment status change
    • menus, widgets, categories, tags, the theme, and the Customizer
    • plugin activation and deactivation, and WordPress, plugin, or theme updates (automatic ones too)
    • site title, tagline, icon, date and time format, home page, posts per page, permalinks, Polylang, and Yoast SEO settings
  • Keeps the cache: saving a draft, uploading media, comments held for moderation, other settings

Edits made outside WordPress (e.g., direct SQL) show up within 10 hours.

6. Verify

Request the home page twice:

for i in 1 2; do curl -so /dev/null -D - https://www.maksonlee.com/ | grep -i x-cache; done

Expected:

x-cache: MISS
x-cache: HIT

Search and login go to PHP:

curl -so /dev/null -D - 'https://www.maksonlee.com/?s=nginx' | grep -i x-cache
curl -so /dev/null -D - https://www.maksonlee.com/wp-login.php | grep -i x-cache

Expected:

x-cache: BYPASS
x-cache: BYPASS

Update a post:

  • Posts → All Posts → hover a post → Quick Edit → Update
Quick Edit on a published post with the Update button

The cache is empty, so the next request goes to PHP again:

for i in 1 2; do curl -so /dev/null -D - https://www.maksonlee.com/ | grep -i x-cache; done

Expected:

x-cache: MISS
x-cache: HIT

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top