💾 缓存配置
静态文件缓存
nginx
server {
# 静态资源强制缓存 30 天(文件名带 hash 的场景)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
# 关闭访问日志(减少 IO)
access_log off;
}
# HTML 文件不缓存(确保用户总是拿到最新版本)
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# 自定义 404 页面
error_page 404 /404.html;
location = /404.html {
internal;
root /var/www/errors;
}
}代理缓存(Proxy Cache)
对于反向代理场景,Nginx 可以缓存后端响应,减少后端压力。适合内容变化不频繁的场景。
nginx
http {
# 定义缓存区域(100MB 内存 + 10GB 磁盘)
proxy_cache_path /var/cache/nginx levels=1:2
keys_zone=my_cache:100m
max_size=10g
inactive=60m
use_temp_path=off;
server {
location /api/ {
proxy_pass http://backend;
# 启用缓存
proxy_cache my_cache;
# 缓存 key(按 URI + 查询参数区分)
proxy_cache_key "$scheme$request_method$host$request_uri";
# 缓存时间(后端没设 Cache-Control 时的默认值)
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 缓存锁——防止缓存击穿(多个请求同时回源)
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
# 添加缓存状态 header(方便调试)
add_header X-Cache-Status $upstream_cache_status;
# 后端自定义缓存控制
proxy_cache_bypass $http_cache_control;
}
}
}bash
# 验证缓存是否生效
curl -I http://example.com/api/data
HTTP/1.1 200 OK
X-Cache-Status: HIT ← 命中缓存
...
X-Cache-Status: MISS ← 未命中(首次访问)
X-Cache-Status: EXPIRED ← 缓存过期
X-Cache-Status: BYPASS ← 跳过缓存
# 清除全部缓存时,先停止写入再删除,避免和 Nginx 正在写缓存冲突
sudo systemctl stop nginx
sudo find /var/cache/nginx -mindepth 1 -maxdepth 1 -exec rm -rf {} +
sudo systemctl start nginx
# 更推荐做定向清理:用 proxy_cache_purge 模块或按业务 key 删除
# proxy_cache_purge 需要额外模块支持FastCGI 缓存(PHP)
nginx
http {
# PHP-FPM 场景的缓存
fastcgi_cache_path /var/cache/nginx/fastcgi
levels=1:2
keys_zone=php_cache:64m
max_size=1g
inactive=60m;
server {
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# 启用 FastCGI 缓存
fastcgi_cache php_cache;
fastcgi_cache_valid 200 5m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
}
}
}