How does Nginx implement caching? How to configure caching strategies?
Nginx provides powerful caching functionality that can cache responses from backend servers, reducing backend load and improving response speed. Nginx supports multiple caching methods including proxy caching and FastCGI caching.
Proxy Cache Configuration:
nginxhttp { # Define cache path and parameters proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m use_temp_path=off; server { listen 80; server_name example.com; location / { proxy_cache proxy_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_bypass $http_cache_control; add_header X-Cache-Status $upstream_cache_status; proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } }
Cache Parameter Explanation:
-
proxy_cache_path: Define cache storage path and parameters
levels: Cache directory hierarchy structurekeys_zone: Shared memory zone name and sizemax_size: Maximum cache sizeinactive: Cache item inactive timeuse_temp_path: Whether to use temporary path
-
proxy_cache: Specify the cache zone to use
-
proxy_cache_valid: Set cache time for different status codes
200 302 10m: Cache 200 and 302 status codes for 10 minutes404 1m: Cache 404 status code for 1 minute
-
proxy_cache_key: Define cache key
-
proxy_cache_bypass: Conditions to bypass cache
FastCGI Cache Configuration:
nginxhttp { fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:10m max_size=1g inactive=60m; server { listen 80; server_name example.com; location ~ \.php$ { fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_methods GET HEAD; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } }
Cache Purging:
The open-source version of Nginx does not support active cache purging. It can be achieved through:
- Set cache expiration time: Control via
proxy_cache_valid - Use third-party modules: Such as ngx_cache_purge
- Manually delete cache files: Delete corresponding files based on cache key
Cache Strategy Configuration:
nginx# Cache based on request method proxy_cache_methods GET HEAD; # Cache based on response headers proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie; # Minimum request count for caching proxy_cache_min_uses 2; # Cache lock to prevent cache stampede proxy_cache_lock on; proxy_cache_lock_timeout 5s; # Cache background update proxy_cache_background_update on; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
Dynamic Cache Control:
nginx# Decide whether to cache based on conditions map $request_uri $skip_cache { default 0; ~*/admin/ 1; ~*/api/ 1; } # Decide whether to cache based on response headers map $upstream_http_cache_control $skip_cache { ~*no-cache 1; ~*private 1; default 0; }
Static File Caching:
nginxlocation ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; }
Cache Status Monitoring:
nginxadd_header X-Cache-Status $upstream_cache_status; # Cache status values: # MISS - Cache miss # BYPASS - Cache bypassed # EXPIRED - Cache expired # STALE - Using stale cache # UPDATING - Cache updating # HIT - Cache hit
Cache Optimization Recommendations:
- Reasonably set cache time, balance freshness and performance
- Use cache keys with necessary parameters to avoid cache conflicts
- Disable caching for dynamic content
- Regularly clean expired cache
- Monitor cache hit rate and adjust cache strategy
- Use cache locks to prevent cache stampede
- Use browser cache for static resources
Complete Configuration Example:
nginxhttp { # Proxy cache proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxy_cache:100m max_size=10g inactive=60m use_temp_path=off; # FastCGI cache fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:100m max_size=10g inactive=60m; # Cache bypass conditions map $request_uri $skip_cache { default 0; ~*/admin/ 1; ~*/api/ 1; ~*/user/ 1; } server { listen 80; server_name example.com; # Static files location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; } # Dynamic content proxy location / { proxy_cache proxy_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_bypass $skip_cache; proxy_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; proxy_pass http://backend; } # PHP files location ~ \.php$ { fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; } } }