乐闻世界logo
搜索文章和话题

How does Nginx implement caching? How to configure caching strategies?

2月21日 16:57

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:

nginx
http { # 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:

  1. proxy_cache_path: Define cache storage path and parameters

    • levels: Cache directory hierarchy structure
    • keys_zone: Shared memory zone name and size
    • max_size: Maximum cache size
    • inactive: Cache item inactive time
    • use_temp_path: Whether to use temporary path
  2. proxy_cache: Specify the cache zone to use

  3. proxy_cache_valid: Set cache time for different status codes

    • 200 302 10m: Cache 200 and 302 status codes for 10 minutes
    • 404 1m: Cache 404 status code for 1 minute
  4. proxy_cache_key: Define cache key

  5. proxy_cache_bypass: Conditions to bypass cache

FastCGI Cache Configuration:

nginx
http { 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:

  1. Set cache expiration time: Control via proxy_cache_valid
  2. Use third-party modules: Such as ngx_cache_purge
  3. 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:

nginx
location ~* \.(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:

nginx
add_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:

  1. Reasonably set cache time, balance freshness and performance
  2. Use cache keys with necessary parameters to avoid cache conflicts
  3. Disable caching for dynamic content
  4. Regularly clean expired cache
  5. Monitor cache hit rate and adjust cache strategy
  6. Use cache locks to prevent cache stampede
  7. Use browser cache for static resources

Complete Configuration Example:

nginx
http { # 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; } } }
标签:Nginx