>_ IzzyLab

Hands-on task

This task is step 20 of the course “nginx basics”

Cache backend responses

hard~20 min

nginx proxies requests to the backend http://127.0.0.1:8800. Enable caching of backend responses on the nginx side and add an X-Cache-Status header that shows cache hits. Different URLs (including ones with different query parameters) are cached separately: the first request to a new URL goes to the backend (X-Cache-Status: MISS), and a repeated one is served from the cache (HIT). The page content must stay the same.

What you'll practise:
  • nginx
  • proxy_cache
  • proxy_cache_path
  • upstream_cache_status
  • caching

Topic breakdown

The proxy cache stores upstream responses on disk, and keys and metadata in shared memory, which is why the storage declaration (proxy_cache_path) lives in the http context while enabling it (proxy_cache) happens in server/location. What gets cached and for how long is determined by proxy_cache_valid together with the response headers: Cache-Control/Expires from the backend are honored by default and can forbid caching. The diagnostic variable $upstream_cache_status shows the outcome of a request (MISS, HIT, EXPIRED, BYPASS, STALE) — it is customary to return it as a header so the cache state is visible to the client and to monitoring.

What's checked

  1. responses are cached: new URL — MISS, repeated request — HIT
  2. page content unchanged

What it looks like