Skip to content
Nginx

Proxy Caching

Cache upstream responses to reduce backend load.

By EZ4Code Team
cacheperformanceproxy

Code

# http block - define a cache zone
proxy_cache_path /var/cache/nginx
    levels=1:2
    keys_zone=api_cache:10m
    max_size=1g
    inactive=60m
    use_temp_path=off;

server {
    listen 80;

    location /api/ {
        proxy_pass http://api_backend;
        proxy_cache api_cache;
        proxy_cache_valid 200 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_use_stale error timeout updating;

        add_header X-Cache-Status $upstream_cache_status;
    }

    # Purge via separate location (with proxy_cache_purge module)
    location ~ /purge(/.*) {
        allow 127.0.0.1;
        deny all;
        proxy_cache_purge api_cache $scheme$request_method$host$1;
    }
}

Explanation

proxy_cache_path defines a shared cache zone, and proxy_cache enables caching per location. proxy_cache_valid sets TTLs per status code, while proxy_cache_use_stale serves cached content during backend failures. The X-Cache-Status header reveals whether a response was HIT, MISS, or EXPIRED.

More Nginx Snippets