User Tools

Site Tools


wiki:nginx_caching

Nginx caching

Example configuration of caching.

Below should be in http context somewhere

proxy_cache_path /var/cache/nginx/mycache
  levels=1:2 keys_zone=de:100M max_size=1G;

Below is valid in http, server, location contexts.

You might want to add $http_user_agent to cache key below to avoid a situation where for example, a mobile site will be served to desktop users if that site has been cached first.

    # caching doesn't work without proxy buffering
    proxy_buffering on;
 
    proxy_cache mycache;
    proxy_cache_key $scheme$proxy_host$uri$is_args$args;
    # caches for responses with status code 200, 301, and 302
    proxy_cache_valid 1d;
    # cache for any other including errors
    proxy_cache_valid any 1m;
    proxy_cache_min_uses 2;
    # bypass cache by providing query arg nocache=1
    proxy_cache_bypass $arg_nocache;
    proxy_cache_lock on;
    proxy_cache_background_update on;
    proxy_cache_use_stale error timeout updating
      http_500 http_502 http_503 http_504;
 
    add_header x-nginx-cache-status $upstream_cache_status;
 
    proxy_ignore_headers Cache-Control;

The proxied backend might send some cache-control headers on its own like with values like private, no-cache, no-store, max-age=0, must-revalidate. We need to discard this. You might also need to ignore headers like Expires and X-Accel-Expires.

The response header x-nginx-cache-status should say “HIT” if the configuration is correct.

Tested on

  • nginx/1.26.0

See also

References

wiki/nginx_caching.txt · Last modified: 2024/06/10 16:36 by antisa

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki