BudiBadu Logo
Samplebadu

Nginx Config by Example: Caching

Nginx 1.x

Improving performance with browser and proxy caching through this code example showing expires directive for cache duration, Cache-Control header configuration, conditional caching by file type, and proxy cache setup for backend responses.

Code

server {
    listen 80;
    root /var/www/html;

    # Cache static assets for a long time
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
        add_header Cache-Control "public, no-transform";
    }

    # Do not cache HTML files (or cache briefly)
    location ~* \.(html|htm)$ {
        expires 1h;
        add_header Cache-Control "private, no-cache, no-store, must-revalidate";
    }

    # Proxy caching (server-side)
    # proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m;
    location /api/ {
        proxy_pass http://backend;
        # proxy_cache my_cache;
        # proxy_cache_valid 200 60m;
    }
}

Explanation

Browser caching is controlled through HTTP headers that instruct clients how long to store files locally. The expires directive adds both Expires and Cache-Control: max-age headers to responses, specifying cache duration. For static assets like images, CSS, and JavaScript that rarely change, long expiry times like 365 days minimize network requests and improve page load performance. The add_header directive provides fine-grained control over Cache-Control directives.

Cache-Control directives include public allowing caching by browsers and intermediate proxies, private restricting caching to browsers only, no-cache requiring revalidation before using cached content, no-store preventing any caching, must-revalidate forcing cache validation when stale, and no-transform preventing proxy modification of content. Dynamic content or frequently updated HTML files should use short cache durations or no caching to ensure users see current content.

Server-side proxy caching stores backend responses on the Nginx server using proxy_cache_path to define cache storage location, directory structure levels, and shared memory zone for cache metadata. The proxy_cache directive activates caching for a location, while proxy_cache_valid specifies cache duration based on response status codes. This dramatically reduces backend load for repeated requests by serving cached responses directly from Nginx without hitting the application server.

Code Breakdown

7
expires 365d sets cache expiration one year in future.
8
add_header Cache-Control manually sets caching directives.
14
no-cache, no-store, must-revalidate prevents caching for dynamic content.
18
proxy_cache_path defines server-side cache storage and metadata zone.