How to Setup Caching on Nginx

A comprehensive guide to configuring caching and compression in Nginx for optimal performance.

Prerequisites

Before configuring caching on Nginx, ensure you have:

  • Nginx installed and running
  • Root or sudo access to the server
  • Basic understanding of HTTP caching concepts
  • Access to nginx.conf or site configuration

Nginx Built-in Cache

Cache Configuration
http {
    proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        location / {
            proxy_cache my_cache;
            proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
            proxy_cache_valid 200 60m;
            proxy_cache_valid 404 1m;
        }
    }
}

Key parameters explained:

  • proxy_cache_path: Defines where cache files are stored
  • levels: Cache file hierarchy levels
  • keys_zone: Shared memory zone for cache keys
  • max_size: Maximum size of the cache
  • inactive: Time after which inactive items are removed

Cache-Control Headers

Static Asset Caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, no-transform";
}

location ~* \.(html|htm)$ {
    expires 1h;
    add_header Cache-Control "public, no-cache";
}

location /api/ {
    add_header Cache-Control "no-store";
    expires 0;
}

Gzip Compression

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;

Compression settings explained:

  • gzip_comp_level: Compression level (1-9)
  • gzip_types: MIME types to compress
  • gzip_vary: Adds Vary: Accept-Encoding header

Configuration Generator

Generated Configuration
http {
    # Cache configuration will appear here
}

Best Practices

Recommended Practices
  • Static Assets:
    • Use long cache times (1 year) with versioned URLs
    • Add Cache-Control: public for CDN caching
    • Enable gzip compression for text-based assets
  • Dynamic Content:
    • Use shorter cache times
    • Implement cache busting for updates
    • Consider using no-cache for user-specific content
  • API Responses:
    • Use no-store for sensitive data
    • Implement ETag headers for validation
    • Consider using Vary header for different responses