A comprehensive guide to configuring caching and compression in Nginx for optimal performance.
Before configuring caching on Nginx, ensure you have:
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:
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 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:
http {
# Cache configuration will appear here
}