Mastering NGINX Content Caching: Configuration, Purging, and Advanced Techniques
This guide explains how to enable and fine‑tune NGINX Plus content caching, covering cache zones, key definitions, loader settings, cache bypass, purge configuration, byte‑range slicing, and practical examples for optimizing performance and reducing backend load.
NGINX can cache static and dynamic content on the web and application server side to speed up delivery to clients and reduce server load.
Overview
When caching is enabled, NGINX Plus stores responses in a disk cache and serves them to clients without proxying the same content each time.
Enabling Response Cache
Include the proxy_cache_path directive in the top‑level http context. The first required parameter is the local filesystem path for cached content; the keys_zone parameter defines the shared memory zone name and size for cache metadata.
http {
# ...
proxy_cache_path /data/nginx/cache keys_zone=mycache:10m;
}Then add the proxy_cache directive in the context where you want to cache responses (e.g., server or location), referencing the zone name defined above.
http {
# ...
proxy_cache_path /data/nginx/cache keys_zone=mycache:10m;
server {
proxy_cache mycache;
location / {
proxy_pass http://localhost:8000;
}
}
}The keys_zone size does not limit the total amount of cached data; the actual cached files are stored on disk. To limit total cache size, add the max_size parameter to proxy_cache_path.
NGINX Processes Involved in Caching
The cache manager periodically checks cache status and removes least‑recently‑used items when the cache exceeds the max_size limit.
The cache loader runs once at NGINX start, loading metadata of previously cached items into shared memory. To avoid a heavy one‑time load, configure iterative loading with loader_threshold , loader_files , and loader_sleeps parameters.
loader_threshold – duration of each iteration in milliseconds (default 200).
loader_files – maximum items loaded per iteration (default 100).
loader_sleeps – pause between iterations in milliseconds (default 50).
Example with a 300 ms iteration threshold and a stop after loading 200 items:
proxy_cache_path /data/nginx/cache keys_zone=mycache:10m loader_threshold=300 loader_files=200;Specifying Requests to Cache
By default, NGINX Plus caches responses to HTTP GET and HEAD requests on the first encounter, using the request URI as the cache key. You can customize the key with proxy_cache_key:
proxy_cache_key "$host$request_uri$cookie_user";Define how many identical requests must be seen before a response is cached with proxy_cache_min_uses: proxy_cache_min_uses 5; To cache methods other than GET and HEAD, list them in proxy_cache_methods:
proxy_cache_methods GET HEAD POST;Limiting or Disabling Cache
Responses are kept indefinitely unless the cache exceeds its configured size. You can set explicit validity periods with proxy_cache_valid or disable caching for certain conditions using proxy_cache_bypass and proxy_no_cache:
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 5m;
proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
proxy_no_cache $http_pragma $http_authorization;Cache Purge
NGINX can delete expired cache files, but you can also purge specific entries on demand. Define a variable that maps the request method to a purge flag:
http {
# ...
map $request_method $purge_method {
PURGE 1;
default 0;
}
}In the location handling cached content, add proxy_cache_purge with the variable:
server {
listen 80;
server_name www.example.com;
location / {
proxy_pass https://localhost:8002;
proxy_cache mycache;
proxy_cache_purge $purge_method;
}
}Send a purge request with a tool such as curl:
$ curl -X PURGE -D – "https://www.example.com/*"
HTTP/1.1 204 No ContentTo restrict who may send purge requests, use a geo block to whitelist IPs and combine it with the earlier map:
geo $purge_allowed {
default 0; # deny others
10.0.0.1 1; # allow this IP
192.168.0.0/24 1; # allow this subnet
}
map $request_method $purge_method {
PURGE $purge_allowed;
default 0;
}Fully Deleting Files from Cache
Enable the built‑in cache purger to iterate over all cache entries and delete those matching a wildcard key:
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m purger=on;Byte‑Range Caching (Cache Slice)
For large files, enable the Cache Slice module to cache partial range requests and fill the cache gradually.
location / {
slice 1m;
proxy_cache cache;
proxy_cache_key $uri$is_args$args$slice_range;
proxy_set_header Range $slice_range;
proxy_cache_valid 200 206 1h;
proxy_pass http://localhost:8000;
}Ensure the module is compiled, set the slice size, include $slice_range in the cache key, enable caching of 206 responses, and forward the range header to the upstream.
Combined Configuration Example
http {
# ...
proxy_cache_path /data/nginx/cache keys_zone=mycache 10m loader_threshold=300 loader_files=200 max_size=200m;
server {
listen 8080;
proxy_cache mycache;
location / {
proxy_pass http://backend1;
}
location /some/path {
proxy_pass http://backend2;
proxy_cache_valid any 1m;
proxy_cache_min_uses 3;
proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
}
}
}In this example, two locations share the same cache but with different caching policies: the first caches infrequently changing responses indefinitely, while the second caches frequently changing responses for only one minute after three identical requests.
Detailed Introduction to NGINX Content Cache
NGINX is a high‑performance HTTP server and reverse proxy that offers content‑caching capabilities, allowing both static and dynamic content to be stored on faster media such as RAM or SSD, thereby improving response speed and reducing backend load.
Why Use NGINX Content Cache
Improved Performance : Frequently accessed content is served from cache, reducing backend requests.
Reduced Latency : Clients receive responses quickly without waiting for upstream processing.
Lower Backend Load : Fewer requests reach the application servers, freeing resources.
Bandwidth Savings : Cached responses avoid repeated data transfer.
How to Configure NGINX Content Cache
Cache configuration is typically placed inside the http, server, or location block.
http {
cache {
levels 1:2;
keys_zone my_cache:10m;
size 1g;
}
server {
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout http_404;
proxy_cache_lock on;
}
}
}The directives define the cache zone, its size, validity periods, stale‑use policies, and locking behavior.
Cache Invalidation and Updates
NGINX follows the rules set by proxy_cache_valid to determine when a cached entry expires. Once expired, the next request triggers a fresh fetch from the upstream server.
Important Considerations
Cache is most beneficial for frequently accessed resources; rarely accessed items may not see noticeable gains.
Cache consumes storage; plan capacity accordingly.
Sensitive, user‑specific data may be unsuitable for caching.
By configuring NGINX content caching wisely, you can significantly boost website performance and response speed while easing the load on backend servers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
