Nginx缓存配置 #

一、缓存概述 #

1.1 Nginx缓存类型 #

类型 说明 适用场景
浏览器缓存 客户端缓存 静态资源
代理缓存 Nginx缓存后端响应 反向代理
FastCGI缓存 缓存FastCGI响应 PHP应用
uWSGI缓存 缓存uWSGI响应 Python应用

1.2 缓存的优势 #

  • 减少后端服务器负载
  • 降低响应延迟
  • 节省带宽
  • 提升用户体验

二、浏览器缓存 #

2.1 expires指令 #

nginx
location ~* \.(jpg|jpeg|png|gif|ico)$ {
    expires 30d;
}

location ~* \.(css|js)$ {
    expires 7d;
}

location ~* \.(html|htm)$ {
    expires 1h;
}

location ~* \.(json|xml)$ {
    expires -1;
}

2.2 expires值说明 #

说明 Cache-Control
epoch 不缓存 no-cache
max 永久缓存 10年
off 不设置
30d 30天 max-age=2592000
-1 不缓存 no-cache

2.3 Cache-Control配置 #

nginx
location /static/ {
    alias /var/www/static/;
    
    expires 1y;
    add_header Cache-Control "public, immutable";
}

location /dynamic/ {
    alias /var/www/dynamic/;
    
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
    add_header Expires "0";
}

2.4 Cache-Control指令 #

指令 说明
public 可被任何缓存存储
private 只能被浏览器缓存
no-cache 使用前需验证
no-store 不缓存
max-age 最大缓存时间(秒)
immutable 资源永不变化
must-revalidate 必须验证过期资源

2.5 ETag配置 #

nginx
location /static/ {
    etag on;
    expires 30d;
}

2.6 Last-Modified配置 #

nginx
location /static/ {
    etag on;
    if_modified_since exact;
    expires 30d;
}

三、代理缓存 #

3.1 缓存区域配置 #

nginx
http {
    proxy_cache_path /var/cache/nginx/proxy 
                     levels=1:2 
                     keys_zone=proxy_cache:10m 
                     max_size=1g 
                     inactive=60m 
                     use_temp_path=off
                     manager_files=100
                     manager_threshold=500ms
                     loader_files=1000
                     loader_threshold=200ms;
}
参数 说明
levels 目录层级,1:2表示两级目录
keys_zone 共享内存区域名称和大小
max_size 最大缓存大小
inactive 不活跃删除时间
use_temp_path 是否使用临时目录
manager_files 一次管理的文件数
loader_files 一次加载的文件数

3.2 启用代理缓存 #

nginx
server {
    location / {
        proxy_pass http://backend;
        
        proxy_cache proxy_cache;
        proxy_cache_key $scheme$request_method$host$request_uri;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
        
        add_header X-Cache-Status $upstream_cache_status;
    }
}

3.3 proxy_cache_valid配置 #

nginx
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301 1h;
proxy_cache_valid any 1m;
proxy_cache_valid 200 302 301 1h;
proxy_cache_valid 404 1m;
proxy_cache_valid any 0;

3.4 缓存状态 #

状态 说明
HIT 缓存命中
MISS 缓存未命中
EXPIRED 缓存过期
STALE 使用过期缓存
UPDATING 缓存更新中
REVALIDATED 重新验证成功
HIT_STALE 命中过期缓存
BYPASS 跳过缓存

3.5 缓存键配置 #

nginx
proxy_cache_key $scheme$request_method$host$request_uri;
proxy_cache_key $scheme$host$request_uri$is_args$args;
proxy_cache_key "$scheme$request_method$host$request_uri$http_cookie";
proxy_cache_key "$request_method|$http_if_modified_since";

3.6 绕过缓存 #

nginx
location / {
    proxy_pass http://backend;
    proxy_cache proxy_cache;
    
    proxy_cache_bypass $http_pragma $http_authorization;
    proxy_no_cache $arg_nocache $cookie_nocache;
}

3.7 条件缓存 #

nginx
map $request_method $skip_cache {
    default 0;
    POST 1;
    PUT 1;
}

map $uri $skip_cache_uri {
    default 0;
    /api/login 1;
    /api/logout 1;
}

location / {
    proxy_pass http://backend;
    proxy_cache proxy_cache;
    
    proxy_cache_bypass $skip_cache $skip_cache_uri;
    proxy_no_cache $skip_cache $skip_cache_uri;
}

3.8 使用过期缓存 #

nginx
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504 
                      updating non_idempotent;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;

四、FastCGI缓存 #

4.1 缓存区域配置 #

nginx
http {
    fastcgi_cache_path /var/cache/nginx/fastcgi 
                       levels=1:2 
                       keys_zone=fastcgi_cache:10m 
                       max_size=1g 
                       inactive=60m;
}

4.2 启用FastCGI缓存 #

nginx
location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    
    fastcgi_cache fastcgi_cache;
    fastcgi_cache_key $scheme$request_method$host$request_uri;
    fastcgi_cache_valid 200 302 1h;
    fastcgi_cache_valid 404 1m;
    
    add_header X-FastCGI-Cache $upstream_cache_status;
}

4.3 WordPress缓存示例 #

nginx
set $skip_cache 0;

if ($request_method = POST) {
    set $skip_cache 1;
}

if ($query_string != "") {
    set $skip_cache 1;
}

if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|sitemap(_index)?.xml") {
    set $skip_cache 1;
}

if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $skip_cache 1;
}

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    
    fastcgi_cache fastcgi_cache;
    fastcgi_cache_key $scheme$request_method$host$request_uri;
    fastcgi_cache_valid 200 301 302 1h;
    fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    
    add_header X-FastCGI-Cache $upstream_cache_status;
}

五、缓存清理 #

5.1 手动清理 #

bash
rm -rf /var/cache/nginx/proxy/*
nginx -s reload

5.2 使用ngx_cache_purge模块 #

nginx
location ~ /purge(/.*) {
    allow 127.0.0.1;
    deny all;
    proxy_cache_purge proxy_cache $scheme$request_method$host$1;
}

清理缓存:

bash
curl -X PURGE http://localhost/purge/path/to/page

5.3 缓存预热 #

bash
#!/bin/bash
URLS=(
    "https://example.com/"
    "https://example.com/about"
    "https://example.com/products"
)

for url in "${URLS[@]}"; do
    curl -s -o /dev/null "$url"
done

六、缓存统计 #

6.1 缓存命中率统计 #

nginx
log_format cache '$remote_addr - [$time_local] "$request" '
                 '$status $body_bytes_sent '
                 'cache_status:$upstream_cache_status';

access_log /var/log/nginx/cache.log cache;

6.2 分析缓存命中率 #

bash
awk '/cache_status:/ {count[$NF]++} END {for (k in count) print k, count[k]}' /var/log/nginx/cache.log

七、缓存配置最佳实践 #

7.1 静态资源缓存 #

nginx
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

location ~* \.(css|js)$ {
    expires 1M;
    add_header Cache-Control "public";
    gzip_static on;
}

location ~* \.(woff|woff2|ttf|eot|otf)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header Access-Control-Allow-Origin "*";
}

7.2 API缓存 #

nginx
location /api/ {
    proxy_pass http://backend;
    
    proxy_cache api_cache;
    proxy_cache_key "$request_method|$request_uri|$http_authorization";
    proxy_cache_valid 200 5m;
    proxy_cache_valid 404 1m;
    proxy_cache_methods GET HEAD;
    
    proxy_cache_bypass $http_x_nocache;
    proxy_no_cache $cookie_nocache;
    
    add_header X-Cache-Status $upstream_cache_status;
}

7.3 动态内容缓存 #

nginx
location / {
    proxy_pass http://backend;
    
    proxy_cache dynamic_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 10m;
    proxy_cache_use_stale error timeout updating;
    
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
    
    add_header X-Cache-Status $upstream_cache_status;
}

八、缓存与CDN #

8.1 CDN回源配置 #

nginx
location / {
    proxy_pass http://backend;
    
    proxy_cache cdn_cache;
    proxy_cache_key $scheme$host$request_uri;
    proxy_cache_valid 200 1d;
    proxy_cache_valid 404 1m;
    
    proxy_ignore_headers Set-Cookie;
    proxy_hide_header Set-Cookie;
    
    add_header X-Cache-Status $upstream_cache_status;
    add_header X-Age $upstream_age;
}

8.2 缓存共享 #

nginx
proxy_cache_key "$scheme$host$request_uri$http_x_forwarded_for";
proxy_cache_valid 200 1h;
proxy_cache_use_stale error timeout updating;
proxy_cache_background_update on;

九、完整配置示例 #

nginx
http {
    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_path /var/cache/nginx/fastcgi 
                       levels=1:2 
                       keys_zone=fastcgi_cache:50m 
                       max_size=5g 
                       inactive=60m;
    
    proxy_cache_key "$scheme$request_method$host$request_uri";
    
    server {
        listen 80;
        server_name example.com;
        
        location /static/ {
            alias /var/www/static/;
            expires 1y;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
        
        location /api/ {
            proxy_pass http://backend;
            
            proxy_cache proxy_cache;
            proxy_cache_valid 200 10m;
            proxy_cache_valid 404 1m;
            proxy_cache_use_stale error timeout updating;
            
            add_header X-Cache-Status $upstream_cache_status;
        }
        
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            
            fastcgi_cache fastcgi_cache;
            fastcgi_cache_valid 200 1h;
            
            add_header X-FastCGI-Cache $upstream_cache_status;
        }
    }
}

十、总结 #

本章我们学习了:

  1. 缓存类型:浏览器缓存、代理缓存、FastCGI缓存
  2. 浏览器缓存:expires、Cache-Control配置
  3. 代理缓存:proxy_cache配置和使用
  4. FastCGI缓存:PHP应用缓存
  5. 缓存清理:手动清理和模块清理
  6. 缓存统计:命中率分析
  7. 最佳实践:不同场景的缓存策略

掌握缓存配置后,让我们进入下一章,学习Gzip压缩!

最后更新:2026-03-27