Caching stores a copy of an upstream response so repeated requests can be served by the proxy instead of regenerating the response in the application. This reduces response time and application traffic, but only non-user-specific content should be cached. section 20.3
Configure a reverse-proxy cache by deciding:
- Which responses to cache, such as a public web page or an API response. section 20.3
- How long responses remain fresh: the example uses one minute for the API and six hours for the web application. section 20.3
- Whether stale content can be served when the upstream has errors, timeouts, invalid headers, or server failures. section 20.3
Verify a cache hit
Reload the nginx configuration, then request the same URL twice. The first response reports X-Cache: MISS and includes X-Upstream, while the repeated request reports X-Cache: HIT and omits X-Upstream because nginx serves the cached response. section 20.3
Listing 20.3 Nginx as a caching reverse proxy for HTTP content
...
location = /api/image {
proxy_pass http:/./iotd/image;
proxy_set_header Host $host;
proxy_cache SHORT;
proxy_cache_valid 200 1m;
...
}
location / {
proxy_pass http:/./image-gallery;
proxy_set_header Host $host;
proxy_cache LONG;
proxy_cache_valid 200 6h;
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
...
}
Use the nginx configuration listing to compare short-lived API caching with longer web-content caching and stale-response handling. section 20.3
Practice with expensive computation
Place a pi-calculation application behind a reverse proxy. Repeating a request for 50,000 decimal places should be much faster from the cache, and cached responses should remain available after the application container is stopped. section 20.6





































