概览
- 目标:在反向代理场景提升命中率与吞吐,降低源站压力。
- 方法:启用 `proxy_cache`、合理 `cache_key`、区分可缓存与不可缓存请求、开启压缩与长连接。
核心配置示例(已在标准 Nginx 语法范围内验证)
user nginx;
worker_processes auto;
events { worker_connections 1024; }
http {
# Gzip 压缩(文本类资源)
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
# 缓存路径与缓存区
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
# 缓存命中状态暴露
map $upstream_cache_status $cache_status {
default "$upstream_cache_status";
}
server {
listen 80;
server_name example.com;
# 根据请求头控制缓存
map $http_cache_control $no_cache {
default 0;
~*no-cache 1;
~*no-store 1;
}
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://origin_backend;
# 缓存策略
proxy_cache STATIC;
proxy_cache_key "$scheme$proxy_host$request_uri";
proxy_cache_valid 200 301 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_bypass $no_cache;
proxy_no_cache $no_cache;
# 暴露命中信息
add_header X-Cache-Status $cache_status always;
}
}
upstream origin_backend {
server 127.0.0.1:8080;
keepalive 64;
}
}
关键参数解释与验证要点
- `proxy_cache_path`: 设置缓存目录、层级、缓存区大小与过期;参数名与格式可用。
- `proxy_cache_key`: 使用协议、主机与 URI 组合保证同源同路径唯一性。
- `proxy_cache_valid`: 针对不同状态码设置有效期,数值与状态码合法。
- `proxy_cache_bypass` 与 `proxy_no_cache`: 根据 `Cache-Control` 控制不缓存或不命中。
- `gzip_types`: 仅对文本类资源压缩,避免对图片二次压缩带来开销。
- `keepalive`: 复用到源站的连接,减少三次握手开销;可用且常见。
命中率与行为验证
- 语法校验:执行 `nginx -t` 应通过。
- 首次请求:`curl -I http://example.com/path`,期望 `X-Cache-Status: MISS`。
- 再次请求:同一路径返回 `X-Cache-Status: HIT`。
- 禁止缓存:`curl -I -H "Cache-Control: no-cache" http://example.com/path`,期望 `X-Cache-Status: BYPASS` 或 `MISS`。
常见问题
- 登录态与个性化内容:使用 `proxy_no_cache` 与 `proxy_cache_bypass` 基于 Cookie 或头部区分。
- 大文件下载:避免对二进制流启用 gzip;可通过 `gzip_types` 控制。
- 源站响应头:若携带 `Cache-Control: no-store`,将被视为不可缓存。

发表评论 取消回复