
Nginx caching lets a reverse proxy reuse an HTTP response instead of asking the application to produce it again. Start with one response that is public, repeated often, and allowed to be slightly out of date. Then check which requests reach the origin and which receive a cached copy.
This guide uses an explicit public catalog route, a counted Python origin, and open-source Nginx 1.31.8. The exact configuration passed 39 functional checks on Windows with Python 3.12.14. These are local behavior tests, not a throughput benchmark or a Hivenet deployment. Nginx documents limitations in its native Windows build; validate your Linux deployment separately.
A public product description can be a reasonable candidate when every eligible reader should see the same version. An account balance, a personalized price, or a permission-dependent document needs a different policy. A route name containing public does not establish that its data is safe to share.
Write down the allowed inputs, the acceptable age, and how changes become visible. Check query parameters and headers that affect the output. Do not put access tokens in a cacheable URL. If an application uses a custom identity header, add its exclusion before enabling caching; the example below checks Authorization and Cookie, not every possible authentication scheme.
This is response caching at the proxy. The FastAPI Redis caching guide covers an application-managed data cache. The Nginx load-balancer guide covers distributing requests and handling failed upstream attempts. Keep those responsibilities separate when diagnosing a result.
Create a separate example directory with empty logs and temp subdirectories. Save the following origin as backend.py. It uses only Python's standard library and counts requests to each URL. Keep ports 19021 and 18084 free. This fixture is for local validation, not a public service.
"""Private test origin. Synthetic data only; never deploy this fixture."""
from collections import Counter
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import threading
from urllib.parse import parse_qs, urlsplit
class Origin(ThreadingHTTPServer):
daemon_threads = True
def __init__(self):
super().__init__(("127.0.0.1", 19021), Handler)
self.counts = Counter()
self.lock = threading.Lock()
self.revision = 1
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
q = parse_qs(urlsplit(self.path).query)
mode = q.get("mode", ["public"])[0]
with self.server.lock:
self.server.counts[(self.command, self.path)] += 1
count = self.server.counts[(self.command, self.path)]
identity = "private" if self.headers.get("Authorization") or self.headers.get("Cookie") else "public"
body = json.dumps({"origin_calls": count, "revision": self.server.revision,
"audience": identity, "method": self.command,
"language": self.headers.get("Accept-Language", "none")}).encode()
status = 503 if mode == "error" else 200
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
controls = {"public": "public, max-age=30", "private": "private, max-age=30",
"no-store": "no-store", "no-cache": "no-cache", "short": "public, max-age=1"}
if mode != "fallback":
self.send_header("Cache-Control", controls.get(mode, "public, max-age=30"))
if mode == "set-cookie":
self.send_header("Set-Cookie", "synthetic=1; HttpOnly")
if mode in ("vary", "vary-star"):
self.send_header("Vary", "*" if mode == "vary-star" else "Accept-Language")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
do_HEAD = do_GET
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
self.do_GET()
if __name__ == "__main__":
with Origin() as server:
try:
server.serve_forever()
except KeyboardInterrupt:
pass
Save the configuration below as nginx.conf in the same directory. Both the origin and proxy bind only to loopback. Our automated checks used a fresh working directory for each run, then stopped the owned processes; no other Nginx installation was changed.
worker_processes 1;
pid logs/nginx.pid;
error_log logs/error.log warn;
events { worker_connections 128; }
http {
log_format cache_check '$request_method $uri $status $upstream_cache_status';
access_log logs/access.log cache_check;
proxy_temp_path temp/proxy;
client_body_temp_path temp/client;
proxy_cache_path cache levels=1:2 keys_zone=public_cache:1m
max_size=20m inactive=10m use_temp_path=off;
map $http_authorization $has_auth { default 1; "" 0; }
map $http_cookie $has_cookie { default 1; "" 0; }
map $http_cache_control $has_cache_control { default 1; "" 0; }
map $http_pragma $has_pragma { default 1; "" 0; }
map $request_method $skip_method { default 1; GET 0; HEAD 0; }
map $upstream_status $skip_status { default 1; 200 0; }
server {
listen 127.0.0.1:18084;
server_name localhost;
location = /healthz { return 204; }
location = /public/catalog {
proxy_pass http://127.0.0.1:19021;
proxy_http_version 1.1;
proxy_set_header Host $proxy_host;
proxy_set_header Connection "";
proxy_connect_timeout 1s;
proxy_read_timeout 2s;
proxy_next_upstream off;
proxy_cache public_cache;
proxy_cache_key "$scheme|$host|$proxy_host|$request_uri";
proxy_cache_methods GET HEAD;
proxy_cache_convert_head on;
proxy_cache_valid 200 3s;
proxy_cache_bypass $has_auth $has_cookie $skip_method
$has_cache_control $has_pragma;
proxy_no_cache $has_auth $has_cookie $skip_method
$has_cache_control $has_pragma $skip_status;
add_header X-Cache-Status $upstream_cache_status always;
}
location / { return 404; }
}
}
The exact-match location limits this experiment to /public/catalog. The key separates scheme, host, upstream, and the original URI including its query string. Two different query strings produced separate entries in our checks. If you later normalize parameters to reduce duplicate entries, first prove that the removed information cannot change the response.
The Boolean maps treat every nonempty Authorization or Cookie value as a reason to skip, including the literal value 0. The policy also skips any request carrying Cache-Control or Pragma. That broad choice is conservative: even a request header that could permit reuse takes the origin path here.
proxy_cache_bypass controls reading from the cache; proxy_no_cache controls saving a response. We apply both request exclusions, then add a response-status exclusion to saving. The proxy module reference describes these directives and the response headers that affect caching.
Start the origin with python backend.py in one terminal. In another, validate and start Nginx using the commands below. Replace /absolute/path/to/example/ with your example directory, keeping its trailing slash; on Windows, use a forward-slash path such as C:/nginx-cache-example/. Use the full path to the executable if it is not on PATH. We tested Nginx 1.31.8 with Python 3.12.14; use a maintained build for deployment and rerun the checks against it.
nginx -p /absolute/path/to/example/ -c nginx.conf -t
nginx -p /absolute/path/to/example/ -c nginx.conf
Request the same URL twice with curl. On Windows PowerShell, use curl.exe to avoid an unrelated shell alias. A clean cache should show MISS followed by HIT. After testing, stop this Nginx instance with the same prefix and configuration arguments plus -s quit, then stop the Python origin with Ctrl+C.
curl -i "http://127.0.0.1:18084/public/catalog?case=manual"
curl -i "http://127.0.0.1:18084/public/catalog?case=manual"
For a cold public URL, our first request returned X-Cache-Status: MISS. The next returned HIT, with the same body and only one origin request. The origin's counter matters: a fast response alone does not show that the cache served it. The local access log records method, path, status, and cache status without query values or credentials.
| Case | Observed result |
|---|---|
| Cold public URL, then the same request | MISS, HIT; one origin call |
| Authorization or Cookie on a warm public URL | BYPASS; public entry remains unchanged |
| Private request before the first public request | BYPASS, MISS, HIT; no private response saved |
| Set-Cookie, private, no-store, no-cache, or Vary: * | Two requests reach the origin twice |
| Different query strings or declared language variants | Distinct entries; later requests HIT their own variant |
| Cold HEAD followed by GET | Origin receives one GET; later GET is a HIT |
| POST twice, then GET twice | Two origin POSTs; GET produces MISS then HIT |
| Expired short-lived response | EXPIRED fetches the new revision; next request HIT |
| 503 with a public freshness header | Not stored under the final status exclusion |
The HEAD check is intentional. In this configuration, a cold HEAD is converted to GET toward the origin and can fill the entry used by a later GET. POST reaches the origin and does not fill that GET entry. The sample's POST handler only returns synthetic data; it performs no business operation.
Test both request orders. First, warm a public entry and send an authenticated request to the same URL. Our response was BYPASS with the synthetic private body. A subsequent anonymous request still received the original public HIT.
Next, make an authenticated request to a cold URL before any public request. The following anonymous request must miss and fetch its own public response. Our Authorization and Cookie fixtures passed this check. Testing only a warm-cache bypass would leave the private-first case unproven.
The synthetic origin deliberately sends misleading public freshness headers in those identity tests. That checks the proxy's request exclusions under an unfavorable condition. Do not copy this behavior into an application: personalized responses need appropriate private or no-store headers for browsers and other caches too. Skipping the Nginx cache does not repair the origin's browser-cache policy.
Separate checks sent Set-Cookie, private, no-store, no-cache, and Vary: * responses. None was stored. A language-varying response with Vary: Accept-Language produced separate English and French entries. Keep these headers meaningful and do not disable their processing merely to raise the hit rate.
The three-second proxy_cache_valid value is a fallback for a successful response without its own freshness information. It is not a universal three-second ceiling. In the test, a response carrying a 30-second max-age remained a HIT after the fallback interval had passed. A one-second response became EXPIRED, fetched the changed origin revision, and then became a HIT again.
We also tested a 503 carrying a public freshness header. Restricting the fallback to status 200 alone did not prevent that error from being stored. The final configuration adds $skip_status to proxy_no_cache, allowing only an upstream 200 to be saved. Two requests for the error then reached the origin twice.
inactive=10m is an unused-entry removal setting, not the content's freshness interval. The 1 MB shared zone holds cache metadata; max_size=20m limits the managed disk cache. Cleanup runs over time, so leave filesystem headroom rather than treating that number as an instantaneous disk quota. These settings are small demonstration values; we did not test size eviction.
A short acceptable freshness interval is the simplest update policy in this example. Versioned URLs can provide a new key, but callers must switch to them and old copies remain until removed. Reloading this configuration is not an invalidation procedure. The official content-caching guide explains removal and purge options; its purge examples require attention to the product edition. This example contains no purge endpoint, cache lock, background refresh, or stale-response policy.
Track hit and miss counts alongside origin requests, response time, disk usage, and errors. A high hit rate is useful only when the reused content is correct. Test changes to authorization, output variants, and origin headers as part of application releases. Keep cache files restricted to the service account, and plan how an empty cache affects origin capacity after a restart or replacement.
If you are choosing the proxy itself, compare Caddy and Nginx. For the hosting decision, the API-hosting guide explains the work a VM leaves with your team.
CPU instances with Compute with Hivenet provide a VM on which you can operate the application and reverse proxy. You manage the cache policy, Linux configuration, TLS, updates, monitoring, disk capacity, and recovery. Use your workload's measurements to choose capacity; these local tests establish neither a cloud speedup nor a cost saving.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.