proxy_cache_pathbelongs in the http block, outside any server block.- The cache key decides what counts as the same page. Get it wrong and visitors see each other's content.
- Write the bypass rules first: never cache a page for a logged-in user or a session cookie holder.
proxy_cache_use_stale updatingkeeps the site fast while the cache refreshes.- Add an
X-Cache-Statusheader so you can see whether the cache is working.
What does an Nginx reverse proxy cache do?
It stores the pages your application produces and serves the next identical request straight from disk, without running PHP or the database. A cached page comes back in a few milliseconds with almost no work. That is why one caching layer usually gains more than any amount of application tuning.
| No cache | Reverse proxy cache hit | |
|---|---|---|
| Work per request | Nginx, PHP-FPM, database, template render | Nginx reads a file |
| Typical response time | 200ms to 2s | 1ms to 10ms |
| Concurrent requests a small VPS handles | Tens | Thousands |
| What a traffic spike costs you | CPU, memory, possibly an outage | Disk reads |
A cache hit skips almost every layer, so the gain is large, not gradual.
This is page caching, not object caching
A reverse proxy cache stores whole finished pages for visitors who are not logged in. Object caching stores the results of single database queries, so it also helps logged-in users and dynamic pages. Most busy sites want both. See WordPress object caching with Redis.
How do I configure proxy_cache_path?
proxy_cache_path sets where the cache lives, how it is indexed and how large it may grow. It belongs in the http block, in nginx.conf or a file included from it. Putting it inside a server block is the most common first mistake, and Nginx will refuse to start.
proxy_cache_path /var/cache/nginx/proxy
levels=1:2
keys_zone=site_cache:100m
max_size=10g
inactive=60m
use_temp_path=off;
# Log the cache result on every request. Without this you are guessing.
log_format cached '$remote_addr - $upstream_cache_status [$time_local] '
'"$request" $status $body_bytes_sent';
access_log /var/log/nginx/access.log cached;| Parameter | Meaning | Sensible value |
|---|---|---|
| levels=1:2 | Nests folders so no single folder holds a million files | 1:2, always |
| keys_zone=name:100m | Memory for keys and metadata only | 100m holds roughly 800,000 entries |
| max_size | Limit for cached content on disk | 10g, or well under your free space |
| inactive | Remove anything not requested in this time | 60m for a busy site, 24h for a quiet one |
| use_temp_path=off | Write straight into the cache folder | off, always: avoids a needless copy |
keys_zone sizes the index in RAM, not the content. max_size is the disk figure.
max_size must fit the disk you have
Nginx fills up to max_size whatever else needs the space. Set 10g on a partition with 12g free and a full disk will eventually stop MySQL writing. Check with df -h /var/cache.
How do I set up the server block?
The server block decides what gets cached, for how long and, most importantly, what never does. Write the bypass rules first. A fast cache that serves one visitor's account page to another is worse than no cache.
server {
listen 443 ssl http2;
server_name example.com;
# ---- Decide what must never be cached, FIRST ----
set $skip_cache 0;
# POST requests and anything with a query string
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
# Admin, login, REST, sitemaps, cron, and the WooCommerce cart, checkout and account pages
if ($request_uri ~* "/wp-admin/|/wp-json/|/xmlrpc.php|wp-.*.php|/feed/|sitemap(_index)?.xml|/cart/|/checkout/|/my-account/") {
set $skip_cache 1;
}
# Anyone with a login, comment or WooCommerce session cookie
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in|woocommerce_items_in_cart|woocommerce_cart_hash") {
set $skip_cache 1;
}
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache site_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 301 302 60m;
proxy_cache_valid 404 1m;
proxy_cache_bypass $skip_cache; # do not SERVE from cache
proxy_no_cache $skip_cache; # do not STORE in cache
# Serve stale content rather than queueing behind a slow backend
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status always;
}
}Set both bypass directives, or you leak private pages
With only proxy_cache_bypass, a logged-in user's page is fetched fresh but still stored, ready for the next anonymous visitor. Set both, every time.
How do I choose the right cache key?
The cache key is what Nginx compares to decide whether two requests want the same page. Too narrow, and visitors share a response they should not. Too broad, and your hit rate collapses because everyone gets their own copy.
# Standard. Right for most sites.
proxy_cache_key "$scheme$request_method$host$request_uri";
# Separate mobile and desktop, if the backend serves different HTML
map $http_user_agent $device {
default desktop;
"~*android|iphone|ipad|mobile|blackberry" mobile;
}
proxy_cache_key "$scheme$request_method$host$request_uri$device";
# Separate by currency or language cookie on a multi-region shop
proxy_cache_key "$scheme$request_method$host$request_uri$cookie_currency";Query strings quietly lower your hit rate. With the config above, any query string skips the cache, so every visit from a link tagged ?utm_source= reaches PHP. For pages that ignore those tags, strip tracking parameters before the request reaches the cache, or build the key from $uri instead of $request_uri.
How do I test that the cache is actually working?
The X-Cache-Status header added above tells you. Request the same page twice: the first should say MISS and the second HIT. If the second still says MISS, something is stopping the page being stored.
# Validate the config, then reload with no dropped requests
sudo nginx -t && sudo systemctl reload nginx
# First request: expect MISS
curl -sI https://example.com/ | grep -i x-cache-status
# Second request: expect HIT
curl -sI https://example.com/ | grep -i x-cache-status
# Confirm the speed difference
curl -s -o /dev/null -w 'first byte: %{time_starttransfer}s\n' https://example.com/
# Live hit rate from the access log (field 3 in the 'cached' log format)
awk '{print $3}' /var/log/nginx/access.log | sort | uniq -c | sort -rn| X-Cache-Status | Means | What to do |
|---|---|---|
| HIT | Served from cache | Working correctly |
| MISS | Not in cache, fetched from the backend | Normal on a first request; a problem if it never changes |
| BYPASS | A bypass rule matched | Expected for admin and logged-in requests |
| EXPIRED | Was cached, had aged out, refetched | Normal. Raise proxy_cache_valid if it happens constantly |
| STALE | Served old content because the backend failed | The backend is down or slow. Investigate that |
| UPDATING | Serving old content while refreshing | Working exactly as intended |
A page with no query string that always shows MISS almost always has a Set-Cookie header, which stops caching.
A Set-Cookie header stops caching without warning
Nginx will not cache a response that sets a cookie, and WordPress themes and plugins set them often. Check with curl -sI https://example.com/ | grep -i set-cookie. If the cookie is harmless, drop it with proxy_ignore_headers Set-Cookie plus proxy_hide_header Set-Cookie, once you are certain it holds nothing specific to the visitor.
How do I purge the cache?
Purging one page with proxy_cache_purge is a paid Nginx Plus feature. On free Nginx you either delete files from the cache folder or compile in the third-party ngx_cache_purge module. Deleting files is crude, but reliable, and needs nothing extra.
# Everything. Blunt, but always works.
sudo find /var/cache/nginx/proxy -type f -delete
sudo systemctl reload nginx
# One URL: the file is named after the MD5 of the cache key
KEY="httpsGETexample.com/about/"
HASH=$(printf '%s' "$KEY" | md5sum | cut -d' ' -f1)
sudo find /var/cache/nginx/proxy -name "$HASH" -delete
# Everything matching a path
sudo grep -rl 'example.com/blog/' /var/cache/nginx/proxy | xargs -r sudo rmClearing the whole cache sends everyone to the backend at once
On a busy site, a full purge sends every visitor to PHP at once, which can turn a cache clear into an outage. proxy_cache_lock on lets one request per page through while the rest wait. Purge single pages where you can.
A cache in front of a slow application hides the problem. Every miss, logged-in visitor and checkout still pays the full cost, so tune what sits behind it too: PHP-FPM tuning and object caching matter most. On G7Cloud, WordPress sites get full-page caching in front of them, set up and maintained by us.
Frequently asked questions
Where does proxy_cache_path go in the Nginx config?
In the http block, usually in /etc/nginx/nginx.conf. It cannot go inside a server or location block: the config test fails with "directive is not allowed here". You then refer to the zone by name with proxy_cache inside the location block.
Why is my Nginx cache always showing MISS?
Most often the response sets a cookie, which stops caching by default. Other causes are a Cache-Control: no-cache header from the backend, a bypass rule matching more than you meant, or a query string that skips the cache or creates a new entry every time.
How do I stop Nginx caching pages for logged-in users?
Set a $skip_cache variable when a login or session cookie is present, then use it in both proxy_cache_bypass and proxy_no_cache. With only bypass set, the private page is still stored and can reach the next anonymous visitor.
What is the difference between proxy_cache_bypass and proxy_no_cache?
proxy_cache_bypass stops Nginx serving a stored response. proxy_no_cache stops it storing the response it gets back. Private content needs both.
How much disk space should I give the Nginx cache?
Enough for your popular pages, with room to spare on the partition. A typical content site needs 1 to 5 GB. Free space is what matters: Nginx fills up to max_size whatever else needs the disk, and a full disk takes the database down.
Can I use an Nginx reverse proxy cache with WooCommerce?
Yes, but the bypass rules must cover the WooCommerce session cookies (woocommerce_items_in_cart and woocommerce_cart_hash) and the cart, checkout and account pages, as in the config above. Cache a checkout page once and customers will see each other's baskets.
About G7Cloud Engineering
Articles written by the engineers who build and run G7Cloud: UK managed hosting and the AI Website Builder. We write about what we operate every day: containers, backups, databases, and the small-business websites that run on them.
More about G7Cloud →