Nginx 反向代理与缓存策略实战
缓存配置(节选)
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m max_size=1g inactive=30m use_temp_path=off;
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/certs/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/privkey.pem;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
location / {
proxy_pass http://upstream_app;
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_cache STATIC;
proxy_cache_valid 200 301 302 10m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_bypass $http_authorization;
add_header X-Cache-Status $upstream_cache_status;
}
}
要点与验证
- 为可缓存的静态与接口响应设置合适的
Cache-Control 与 ETag。
- 通过
curl -I 或日志中的 X-Cache-Status 验证缓存命中情况(HIT/BYPASS/MISS)。
- 启用 HTTP/2 与压缩提升传输效率;TLS 证书与密钥路径需正确配置。
发表评论 取消回复