cache-purge: NGINX cache purge and tag invalidation module
Requires the Pro plan (or higher) of the GetPageSpeed NGINX Extras subscription.
Installation
You can install this module in any RHEL-based distribution, including, but not limited to:
- RedHat Enterprise Linux 7, 8, 9 and 10
- CentOS 7, 8, 9
- AlmaLinux 8, 9
- Rocky Linux 8, 9
- Amazon Linux 2 and Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install nginx-module-cache-purge
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install nginx-module-cache-purge
Enable the module by adding the following at the top of /etc/nginx/nginx.conf:
load_module modules/ngx_http_cache_purge_module.so;
This document describes nginx-module-cache-purge v2.9.1 released on Nov 13 2026.
Selectively purge content from NGINX's FastCGI, proxy, SCGI, and uWSGI caches using HTTP PURGE requests — no filesystem hacks, no permission headaches.
This is a feature present in NGINX Plus, but ngx_cache_purge brings it to open-source NGINX.
Key Features
- Same-location purging — add
PURGEsupport directly to existing cache locations, no extralocationblocks needed - Wildcard purging — purge multiple cache entries with a single request using
* - Cache tags / surrogate keys — invalidate only objects whose cached response tags match a trusted PURGE pattern
- Bulk purge — clear all cached content at once with
purge_all - Non-blocking bulk purges — full-zone walks run in a thread pool, so a purge of a million-file cache does not stall the worker
- Instant prefix and zone purges — with generation keys a purge of a prefix or of everything takes the same fraction of a millisecond on any cache size, and survives a restart
- Refresh instead of purge —
REFRESHkeeps the cached entries and makes NGINX revalidate them with the origin, so unchanged content is never downloaded again - IP-based access control — restrict who can issue purge requests
- Cache key method substitution — purge GET-cached content even when
$request_methodis in your cache key - Configurable response format — get purge results in HTML, JSON, XML, or plain text
- All cache types — works with FastCGI, proxy, SCGI, and uWSGI
Quick Start
Add PURGE support to any cached location:
http {
proxy_cache_path /var/cache/nginx keys_zone=my_cache:10m max_size=1g;
server {
location / {
proxy_pass http://127.0.0.1:8000;
proxy_cache my_cache;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_purge PURGE from 127.0.0.1;
}
}
}
Purge a cached page:
curl -X PURGE https://example.com/page-to-purge
That's it. No separate /purge location, no filesystem permissions to manage.
Configuration Directives
Same-Location Syntax (Recommended)
Enables purging directly in the location that serves cached content.
fastcgi_cache_purge
- syntax:
fastcgi_cache_purge on|off|<method> [purge_all] [from all|<ip> [.. <ip>]] - default:
none - context:
http,server,location
proxy_cache_purge
- syntax:
proxy_cache_purge on|off|<method> [purge_all] [from all|<ip> [.. <ip>]] - default:
none - context:
http,server,location
scgi_cache_purge
- syntax:
scgi_cache_purge on|off|<method> [purge_all] [from all|<ip> [.. <ip>]] - default:
none - context:
http,server,location
uwsgi_cache_purge
- syntax:
uwsgi_cache_purge on|off|<method> [purge_all] [from all|<ip> [.. <ip>]] - default:
none - context:
http,server,location
Separate-Location Syntax
Use a dedicated location for purge requests. Useful when you need different access rules for purging.
fastcgi_cache_purge
- syntax:
fastcgi_cache_purge zone_name key - context:
location
proxy_cache_purge
- syntax:
proxy_cache_purge zone_name key - context:
location
scgi_cache_purge
- syntax:
scgi_cache_purge zone_name key - context:
location
uwsgi_cache_purge
- syntax:
uwsgi_cache_purge zone_name key - context:
location
Response Format
cache_purge_response_type
- syntax:
cache_purge_response_type html|json|xml|text - default:
html - context:
http,server,location
Example with JSON responses:
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key "$uri$is_args$args";
proxy_cache_purge PURGE from 127.0.0.1;
cache_purge_response_type json;
}
{"Key": "httplocalhost/"}
Purge Result Contract
Every successful purge response includes a Cache-Purge-Result header. Its
value is an HTTP Structured Fields
Item whose primary token identifies the operation and whose count parameter
reports how many cache objects were invalidated or deleted:
Cache-Purge-Result: exact; count=1
Cache-Purge-Result: wildcard; count=12
Cache-Purge-Result: all; count=47
Cache-Purge-Result: tags; count=3
Two more forms exist for the opt-in features below:
Cache-Purge-Result: refresh; count=3
Cache-Purge-Result: wildcard; generation=42
Cache-Purge-Result: all; generation=43
Cache-Purge-Result: exact; count=1; generation=44
The operation tokens have these meanings:
exact: an exact cache key was invalidated, including a key found through*_cache_purge_key_methodsubstitution. When the cached response carries aVaryheader, every stored variant of the key is deleted andcountreports the number of cache files removed (the primary entry plus each secondary-key variant).wildcard: cache files matching a key prefix ending in*were deleted.all: cache files in the configured cache zone were deleted bypurge_all.tags: cache files whose stored tag header matched the request pattern were deleted. A successful no-match tag purge returnstags; count=0.refresh: aREFRESHrequest expiredcountcache files in place, whatever it selected them by. Nothing was deleted.
The generation parameter is present when the purge was carried out by
raising a generation; its value is the serial number of
that purge in the zone. A wildcard or all purge done this way has no
count: it deletes nothing at the time, so there is nothing to count. An
exact one reports the entry it removed.
The contract is identical for FastCGI, proxy, SCGI, and uWSGI caches because all four backends use the same result-recording and response code. Existing response bodies, content types, and status codes are unchanged.
A bulk purge answered before its job has finished (only possible with
cache_purge_wait set to off or a time) returns
202 Accepted and carries the boolean pending parameter instead of a count:
HTTP/1.1 202 Accepted
Cache-Purge-Result: all; pending
The purge has been accepted and will be carried out; its outcome is written
to the error log when the job finishes. Consumers that need the count must
leave cache_purge_wait at its default.
The header is emitted only after an operation completes successfully. It is absent from authorization failures, invalid tag patterns, exact-key misses, unsupported locations, and internal failures. It is also absent from module versions that predate this contract. Consumers that require a particular operation, such as tag invalidation, must treat an absent header or a different operation token as unsupported rather than inferring success from HTTP 200.
The field has no separate version parameter. Its initial grammar is additive: consumers must ignore unknown parameters, while any incompatible future contract would require a different field name.
Cache Key Method Substitution
When $request_method is part of your cache key, purge requests generate a different key (PURGE vs GET) and won't find the cached entry. These directives solve that:
*_cache_purge_key_method
- syntax:
fastcgi_cache_purge_key_method <method> [<method> ...] - context:
http,server,location
Available for all cache types: fastcgi_cache_purge_key_method, proxy_cache_purge_key_method, scgi_cache_purge_key_method, uwsgi_cache_purge_key_method.
location ~ \.php$ {
fastcgi_cache WORDPRESS;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_purge PURGE from 127.0.0.1;
fastcgi_cache_purge_key_method GET; # Substitutes GET for PURGE in key lookup
}
You can specify multiple methods:
fastcgi_cache_purge_key_method GET HEAD;
Vary Variant Index
cache_purge_variant_index
- syntax:
cache_purge_variant_index <size> | off - default:
8m - context:
http
Since 2.6.2 an exact purge of a key whose cached response carries a Vary
header deletes every stored variant. Variant file names are derived from each
requesting client's header values, so they cannot be computed from the purge
request alone; without extra bookkeeping the module finds them by scanning
every file in the cache zone. The scan is correct but costs O(zone size) per
Vary'd purge. Since 2.8.0 it runs in the background
and no longer blocks the worker, but the purge request still waits that long
for its answer (measured on a single-worker zone of small files, Linux ext4,
Apple M2; "warm" means the page cache already holds the zone):
| Files in zone | First purge (cold page cache) | Repeat purge (warm) | Non-Vary purge |
|---|---|---|---|
| 10,000 | 0.5 s | 0.03 s | 0.2 ms |
| 100,000 | 4.5 s | 0.2 s | 0.2 ms |
| 1,000,000 | 227 s | ~1 s | 0.1 ms |
The variant index removes this cost for repeat purges. It is a shared-memory map from each purged primary key to the variant hashes stored or served for it afterwards, letting the next exact purge unlink exactly those files in O(variants): on the same setup, indexed purges measured 0.2–2 ms regardless of zone size, including the 1,000,000-file zone. Correctness is never traded for speed: a key's first exact purge in an nginx instance's lifetime always scans (and seeds the index), and the index is consulted only while its record is provably complete — a restart, eviction under index memory pressure, or more than 64 variants on one key all drop the record and the next purge falls back to the scan, which re-seeds it. Stale index entries (variant files already evicted by the cache manager) are skipped harmlessly.
The default 8 MB zone tracks tens of thousands of purged keys; size it up for
very large purge-heavy deployments, or set off to always use the scan.
Non-Vary purges never scan and never touch the index.
The benchmark above is reproducible with
bench/variant_scan_bench.sh.
WordPress Integration
FastCGI Cache + Purge
A complete WordPress setup with caching and automatic purge support:
http {
fastcgi_cache_path /var/cache/nginx levels=1:2
keys_zone=WORDPRESS:100m max_size=1g
inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$host$request_uri";
server {
listen 80;
server_name example.com;
root /var/www/wordpress;
index index.php;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp|avif)$ {
expires max;
log_not_found off;
}
location / {
try_files $uri $uri/ /index.php?$args;
fastcgi_cache_purge PURGE from 127.0.0.1;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
fastcgi_cache_use_stale error timeout updating;
fastcgi_cache_lock on;
fastcgi_cache_purge PURGE from 127.0.0.1;
add_header X-Cache-Status $upstream_cache_status always;
}
}
}
Why fastcgi_cache_purge in both locations? The root URL / is a special case. When try_files checks $uri/, it finds the document root directory. For GET requests, the index directive routes to index.php — but for PURGE requests, index doesn't apply and NGINX stops at location /. Adding fastcgi_cache_purge there ensures PURGE / works.
Proxy Cache Purge Plugin
Install the Proxy Cache Purge plugin to automatically purge cache when content is updated:
wp plugin install varnish-http-purge --activate
wp option update vhp_varnish_ip '127.0.0.1'
The plugin sends PURGE requests to NGINX whenever posts, comments, or pages are modified — no manual cache management needed.
Cache Key Best Practices
Keep it simple — avoid $request_method in keys
# Recommended
fastcgi_cache_key "$scheme$host$request_uri";
# Avoid — purge requests won't match cached GET entries
fastcgi_cache_key "$scheme$request_method$host$request_uri";
If you must include $request_method, use *_cache_purge_key_method GET to fix purge key lookups.
Wildcard Purging
Purge multiple entries matching a pattern by appending *:
curl -X PURGE https://example.com/blog/*
The asterisk must be the last character. For this to work, $uri must be at the end of your cache key.
The match is case-sensitive, like NGINX cache keys themselves: /Blog/* does not purge /blog/... (it did before 2.7.2).
Cache Tags / Surrogate Keys
cache_purge_tags connects a tag header stored in cached upstream responses to
a regex header on an authorized PURGE request:
location / {
proxy_pass http://backend;
proxy_cache app_cache;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_purge PURGE from 127.0.0.1;
cache_purge_tags X-Magento-Tags X-Magento-Tags-Pattern;
}
- syntax:
cache_purge_tags <cached-response-header> <purge-pattern-header> - default:
off - context:
http,server,location
For Magento Open Source and Adobe Commerce, no application change is needed.
Magento already adds X-Magento-Tags to cacheable responses and sends trusted
localhost PURGE requests with X-Magento-Tags-Pattern. The module scans the
same cache zone and removes only matching objects. A tag pattern takes
precedence over exact-key, wildcard, and purge_all behavior for that request.
The response tag header may be hidden from clients with proxy_hide_header.
It remains available in NGINX's on-disk cache metadata for invalidation. An
invalid regex returns HTTP 400; a valid pattern with no matches returns HTTP
200, matching Magento's generated Varnish VCL.
Tag invalidation scans cached header metadata only when a PURGE arrives. Normal cache hits pay no tag-index overhead, but purge time grows with the number of files in the cache zone. This trades Varnish's persistent ban list for immediate deletion of matching NGINX objects.
WordPress cache-tag integrations can use the same directive with their header names:
cache_purge_tags X-Cache-Tags X-Cache-Tags-Pattern;
Bulk Purge
Clear all cached files at once:
proxy_cache_purge PURGE purge_all from 127.0.0.1;
On a large cache or slow storage this takes a while. The purge request waits for it, but the worker does not: see Background Purge Queue.
Generation Keys
A wildcard purge and purge_all have to visit every file of the cache zone:
see the table below. Generation keys remove the
walk. The cache key carries a generation number, a purge raises the number of
what it covers, and entries stored under the old number can no longer be
found. The purge is a few memory writes, whatever the size of the cache.
http {
proxy_cache_path /var/cache/nginx keys_zone=my_cache:100m max_size=10g;
cache_purge_generation_zone gen:1m state=/var/lib/nginx/purge-gen.state;
server {
location / {
proxy_pass http://backend;
proxy_cache my_cache;
cache_purge_generation_key gen "$scheme$host$request_uri";
proxy_cache_key $cache_purge_generation_key;
proxy_cache_purge PURGE from 127.0.0.1;
}
}
}
curl -X PURGE 'https://example.com/blog/*' # Cache-Purge-Result: wildcard; generation=1
curl -X PURGE https://example.com/blog/post # Cache-Purge-Result: exact; count=1; generation=2
What you write as the cache key today goes into
cache_purge_generation_key, and the cache key becomes the variable. It
works the same for fastcgi_cache_key, scgi_cache_key and
uwsgi_cache_key, and with the separate-location syntax:
location ~ /purge(/.*) {
cache_purge_generation_key gen "$scheme$host$1$is_args$args";
proxy_cache_purge my_cache $cache_purge_generation_key;
}
What changes for a location that uses it:
- A wildcard purge and
purge_allare instant and answer with agenerationinstead of acount. - An exact purge covers every
Varyvariant at once, without the variant index and without a scan. It still removes the entry and answers412when the key was not cached. - A response that was being fetched while its key was purged is not served. It lands under the old generation. A classic purge cannot catch it: the file does not exist yet when the purge deletes.
- Matching is byte-exact, as with cache keys themselves.
- Purges survive a restart, a reload and a binary upgrade. They are kept in the state file and each one is written to disk before it is answered.
- Cache tag purges are unchanged: they walk the zone.
- An exact purge answers
412when the key's primary entry is not on disk; its generation is raised all the same.
Things to know:
- The variable must be the whole cache key. If it is only a part of one,
or the location does not use it, purges there are carried out the classic
way, by deleting and walking. A location that uses the variable in its
cache key without a
cache_purge_generation_keyis refused when the configuration is read: the variable would be empty there and everything would be cached under one key. - Do not mix key styles in one cache zone. A wildcard purge or
purge_allon a generation-key location covers what was cached through that zone of generations. Entries of the same*_cache_pathstored under other cache keys are not touched by it. - Purged files stay on disk for a while. They are unreachable, count
against
max_size, and are removed by a sweep that runs in the background queue aftersweep=has passed since a purge. Withsweep=off, orcache_purge_queue 0, NGINX removes them itself, as the least recently used entries or afterinactive. - An exact purge also invalidates a few unrelated keys. Exact purges are
recorded in a fixed table of buckets, and keys that share a bucket are
invalidated together: on average one key in every
bucketsof the zone (65,536 for a 1 MB zone). They cost a cache miss, never a stale response. - A zone holds a limited number of purged prefixes. A 1 MB zone has
16,384 slots in groups of 16. A prefix purged again reuses its slot, and
purge_allfrees all of them. Each prefix can go into either of two groups; when a new prefix finds both full, which starts to happen when the zone is about nine tenths used, the whole zone is purged instead andcache purge generation zone "..." has no room for prefixis logged aterrorlevel: nothing stale is served, the cache is refilled. Size the zone for the number of distinct prefixes you purge between twopurge_all; the status variables show how many slots are in use and how often this has happened. - A purge that cannot be written to disk is answered
500. Whenmsync()of the state file fails, as on a failing disk, the purge still takes effect at once, but a crash of the host could undo it, so it is not acknowledged. The next purge that is written takes all earlier ones to disk with it. While the failure lasts, the slots of purged prefixes cannot be freed, not even bypurge_all, and a new prefix that finds no slot purges the whole zone: nothing stale is served, the cache is refilled more often. The first failure is logged atcritlevel and the first such whole-zone purge aterror, once each for all workers; the following ones are logged atinfoand counted in$cache_purge_generation_sync_failures_<zone>. The first purge that is written again is logged atnotice, and frees the slots. NGINX does not start on a state file it cannot write. - A prefix longer than 4096 bytes is purged by a walk, as before.
- Removing or losing the state file invalidates everything cached under the zone, because the generations are gone with it. So does changing the size of the zone, which NGINX refuses to do while the file exists.
- Never put an older copy of the state file back (a backup, a snapshot) while keeping the cache directory: it lowers generations, and entries that were purged since the copy was taken are served again. Remove the file instead.
- Each distinct length of a purged prefix adds a probe to the key lookup of every request with a key at least that long, until the state file is replaced. The cost is in the table below.
- With
$slice_range,$request_methodor other parts in the key, put them into the logical key like any other part. - 64-bit platforms only.
cache_purge_generation_zone
- syntax:
cache_purge_generation_zone <name>:<size> state=<file>|off [sweep=<time>|off] - default:
none - context:
http
Declares a zone of generations. state=<file> is where purges are kept; the
file is created by the master process with mode 0600 and has the size of
the zone, in a directory that must exist. state=off keeps them in memory
only: a restart or a binary upgrade then invalidates everything cached under
the zone, a reload does not, and while a binary upgrade is in progress a
purge reaches only the workers of the binary that took it. The parameter is
mandatory so that the choice is a deliberate one.
sweep (default 5m) is how long after a purge the unreachable files are
swept from the cache path.
cache_purge_generation_key
- syntax:
cache_purge_generation_key <zone> <key> - default:
none - context:
http,server,location
Sets the logical cache key of the location and makes
$cache_purge_generation_key available, which expands to
cpg1:<zone>:<epoch>:<generation>:<key>.
Status variables
$cache_purge_generation_<counter>_<zone> is a counter of the zone named
<zone>, for a status location or a log format. A - in the name of the
zone is written _. The counters are kept in the state of the zone: every
worker shows the same values, and with a state file they go on across
restarts.
| Variable | Value |
|---|---|
$cache_purge_generation_serial_<zone> |
Serial number of the latest purge, which is the number of purges the zone has recorded |
$cache_purge_generation_baseline_<zone> |
Serial number of the latest purge of the whole zone: a purge_all, or a prefix purge that found no slot |
$cache_purge_generation_prefixes_<zone> |
Slots in use: the prefixes purged since the latest purge of the whole zone |
$cache_purge_generation_slots_<zone> |
Slots the zone has |
$cache_purge_generation_overflows_<zone> |
Prefix purges that found no slot and purged the whole zone instead. If it rises while sync_failures does not, the zone is too small |
$cache_purge_generation_sync_failures_<zone> |
Times the state could not be written to disk. Each one is a purge answered 500 |
location = /purge-status {
allow 127.0.0.1;
deny all;
return 200 "prefixes $cache_purge_generation_prefixes_gen
slots $cache_purge_generation_slots_gen
overflows $cache_purge_generation_overflows_gen
sync_failures $cache_purge_generation_sync_failures_gen
";
}
prefixes counts the slots each time it is used, 16,384 of them for a 1 MB
zone: keep it out of the log format of a busy server. A variable that names
no zone is empty. The variables need NGINX 1.11.10 or newer.
Measurements
One worker, Linux ext4 in Docker on an Apple M2, a zone of small files; a wildcard purge that matches nothing, so the walk only reads. The generation purge includes writing the state file to disk.
| Files in zone | Wildcard purge by walk | By generation |
|---|---|---|
| 100,000 | 0.24–0.76 s | 0.6–1.4 ms |
| 1,000,000 | 70–121 s | 1.3–3.2 ms |
What the generation lookup costs a cache hit, as requests per second of one
worker serving one small cached response (wrk, 16 connections, best of
three 5-second runs; runs of the same case differ by about 5% on this setup):
| Cache key | Requests/s |
|---|---|
| plain | 118,900 |
| generation key, nothing purged | 109,700 |
| generation key, 1,000 prefixes purged | 115,900 |
| generation key, 101,000 prefixes purged | 107,800 |
| generation key, a purged prefix of every length up to the key's (49) | 95,100 |
The number of purged prefixes does not matter, the number of their distinct
lengths does: the last row is the worst case for a 50-byte key and costs
about 2 microseconds per request. Reproducible with
bench/generation_bench.sh.
Refresh
A purge deletes: the next visitor waits for the origin, and the whole
response is downloaded again even if it has not changed. REFRESH marks the
selected entries expired and leaves them in place. NGINX then revalidates
each one with a conditional request the next time it is asked for: an origin
that answers 304 Not Modified keeps the cached body, one that answers 200
replaces it.
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_revalidate on;
proxy_cache_use_stale updating;
proxy_cache_background_update on;
proxy_cache_purge PURGE from 127.0.0.1;
cache_purge_refresh_method REFRESH;
}
curl -X REFRESH https://example.com/page # Cache-Purge-Result: refresh; count=1
curl -X REFRESH 'https://example.com/blog/*' # Cache-Purge-Result: refresh; count=37
- It selects what a purge selects: an exact key with all its
Varyvariants, a wildcard, everything (purge_all), cache tags, and purge key methods. The same access list applies. An exact key that is not cached answers412. - It works on every cache type and needs no generation keys. On a location with generation keys a wildcard matches the logical key.
*_cache_revalidate onis what saves the download. Without it, or when the origin sends noETagorLast-Modified, a refreshed entry is fetched again in full, like a purged one.- With
*_cache_use_stale updatingand*_cache_background_update onno visitor waits: the first request after a refresh is answered from the cache while NGINX revalidates in the background. That one response may be the old content. With*_cache_use_stale error, the old content is also served while the origin is down. Use a purge when the old content must not be served again. - Wildcard,
purge_alland tag refreshes walk the zone in the background queue, like the purges. They expire what was cached before the request. - A response that was already on its way into the cache when the refresh arrived is stored as fresh.
cache_purge_refresh_method
- syntax:
cache_purge_refresh_method <method> - default:
none - context:
http,server,location
The request method that refreshes instead of purging, in a location that has
a *_cache_purge directive. In a separate purge location, requests with this
method refresh and all others purge.
Background Purge Queue
purge_all, wildcard and cache tag purges, and the Vary variant scan of an
exact purge, have to visit every file in the cache zone. Before 2.8.0 that
walk ran inside the request handler, so the worker process served nothing
else until it ended: a fraction of a second on a small warm cache, minutes on
a million files read from a cold disk.
Since 2.8.0 each of these purges becomes a job in a per-worker queue. Its
walk runs in an NGINX thread pool, so the
event loop does no disk work for it and keeps serving other requests. The
purge request itself stays open and is answered when its job finishes, with
the same 200 response and Cache-Purge-Result ... count=N header as
before. Nothing changes for existing integrations.
What a job does and does not purge:
- Entries cached before the purge request are removed. Entries stored
after it survive, even though the walk is still running: a long purge does
not keep deleting content that is already fresh. The boundary is taken from
the cache filesystem's own clock and errs on the side of purging by the
timestamp granularity, about 10 ms (1 s on filesystems with whole-second
timestamps). An entry the origin revalidated (
304) after the purge request counts as stored after it and survives too. - Identical purges are coalesced. Requests for the same purge that arrive while one is waiting to start share a single pass. A pass that is already running is never shared, because it may have left directories that hold entries the new request must remove; such a request gets the next pass. A burst of identical purges therefore costs at most two walks.
- A client that disconnects does not cancel its job.
- The cache zone accounting is updated for every removed file. Earlier
releases left the removed entries counted against
max_sizeuntil they expired, and the cache manager then logged a failedunlink()for each. - Only cache entries are touched: regular files whose name is a cache key hash. Temporary files of responses being written are left alone.
On reload, the old worker finishes its queue before it exits. A fast shutdown
(nginx -s stop), or a crash, abandons the jobs of that worker; a stop logs
each of them at warn level. Each finished job logs one line at notice
level:
cache purge job #7 wildcard "/blog/" in "/var/cache/nginx" finished: removed 1830 file(s) in 412 ms, kept 3 stored after the request, 0 error(s)
Where NGINX is built without thread support, the same walk runs on the event loop in slices of a few milliseconds instead. Other requests are then delayed by one slice at most, rather than not at all.
What other requests to the same worker experience while a purge walks the whole zone (one worker, zone of small files, Linux ext4 in Docker on an Apple M2; a client requests a trivial location in a loop during the walk; the 1,000,000-file zone does not fit the page cache, so its repeat walks are not warm):
| Files in zone | Page cache | Purge takes | Slowest other request before 2.8.0 | Since 2.8.0 |
|---|---|---|---|---|
| 100,000 | cold | 4.4–6.0 s | 4.4 s | 1.7 ms |
| 100,000 | warm | 0.19 s | 0.19 s | 0.8 ms |
| 1,000,000 | cold | 89 s | 89 s | 17 ms |
| 1,000,000 | repeat | 61–75 s | 64–75 s | 14 ms |
"Before 2.8.0" is measured as cache_purge_queue 0, which runs the same walk
on the event loop the way earlier releases did. Reproducible with
bench/worker_latency_bench.sh.
cache_purge_queue
- syntax:
cache_purge_queue <number> - default:
128 - context:
http
How many jobs may wait in a worker's queue, not counting the one running. A
purge that arrives when the queue is full is carried out synchronously, as
before 2.8.0, and logs cache purge queue is full, purging synchronously at
warn level. 0 disables the queue: every bulk purge then runs
synchronously and blocks the worker.
cache_purge_thread_pool
- syntax:
cache_purge_thread_pool <name> - default: the
defaultthread pool - context:
http
The thread pool that runs the walks. A worker runs one job at a time, so a single thread is enough:
thread_pool purge threads=1;
http {
cache_purge_thread_pool purge;
}
cache_purge_wait
- syntax:
cache_purge_wait on | off | <time> - default:
on - context:
http,server,location
How long a bulk purge request waits for its job. on waits until the job is
done and answers 200 with the count. With a time, a request whose job is
not done by then is answered 202 Accepted with a
pending result, and the job carries on; off
answers 202 at once. Exact purges that need no scan are answered
immediately in every case.
location ~ /purge(/.*) {
proxy_cache_purge ZONE $1$is_args$args;
cache_purge_wait 2s;
}
IP-Based Access Control
Restrict purge requests to trusted sources:
fastcgi_cache_purge PURGE from 127.0.0.1 192.168.1.0/24;
Symlinks Inside the Cache Path
Since 2.7.1, bulk purges (purge_all, wildcard, cache tags and the Vary
variant scan) skip any symlinked directory found below the cache path and log
cache purge skipped symlinked directory "..." at warn level. NGINX never
creates symlinks there, so one is either a mistake or an attempt to make a
purge delete files elsewhere. A *_cache_path that is itself a symlink is
fine.
Troubleshooting
| Response | Cause | Fix |
|---|---|---|
| 405 Not Allowed | PURGE hit a location without *_cache_purge |
Add *_cache_purge to all relevant locations |
| 412 Precondition Failed | Cache entry not found (never cached, already expired, or key mismatch) | Check cache key — look for $request_method issues. On releases before 2.6.2, an upstream Vary header (e.g. Vary: Accept-Encoding) also caused 412 unless the purge request carried the exact same header value as the cached variant; upgrade, or work around with proxy_ignore_headers Vary |
| 403 Forbidden | Client IP not in from list |
Add your IP to from |
| 200 OK but cache persists | $request_method in cache key creates mismatched keys |
Remove $request_method from key, or add *_cache_purge_key_method GET |
Purge answers generation= but no count |
The location uses generation keys: nothing is deleted at purge time | Expected. The removed files are counted in the cache purge job ... sweep log line |
| Everything is a miss after a restart | A generation zone with state=off, or its state file was removed |
Use state=<file> on a path that survives restarts |
| 500 on a purge of a generation-key location | The state file could not be written to disk; msync() of cache purge generation state ... failed is in the error log at crit level |
The purge is in effect. Fix the disk or filesystem under the state file; the next purge that is written is answered 200 again |
| The whole cache is refilled after a prefix purge | The prefix found no slot: $cache_purge_generation_overflows_<zone> has risen |
Use a larger zone (remove the state file to resize it), or purge fewer distinct prefixes between two purge_all |
| 202 Accepted | cache_purge_wait is off or expired: the purge is still running |
Read the outcome from the cache purge job line in the error log, or leave cache_purge_wait at on |
| Purge request times out, cache is purged anyway | The client gave up before a long bulk purge finished; the job is not cancelled | Raise the client timeout, or set cache_purge_wait to answer 202 |
Vary / gzip_vary interaction: When the upstream response carries a Vary
header (for example Vary: Accept-Encoding, or nginx's own
gzip_vary), nginx stores one variant per
distinct request header value under the same cache key. Since 2.6.2 an exact
purge deletes every stored variant of the key and reports the number of files
removed in Cache-Purge-Result: exact; count=N; since 2.7.0 repeat purges of
a key use the variant index instead of scanning
the cache zone. On older releases an exact
purge only removed the variant matching the purging request's own headers
(usually returning 412); there, work around it with
proxy_ignore_headers Vary in the
cached location, or disable gzip_vary.
Testing
ngx_cache_purge includes a test suite based on Test::Nginx:
prove
See Also
- Supercharging WordPress with NGINX Cache Purge — full setup guide
- NGINX Proxy Cache & Microcaching — proxy cache fundamentals
- NGINX fastcgi_cache_purge docs — NGINX Plus reference