Nginx的反向代理缓存功能可以显著提高网站性能,减少后端服务器负载。以下是详细的配置方法:
http {
# 定义缓存路径和参数
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
# 其他http配置...
}
参数说明:
- /var/cache/nginx
:缓存文件存储路径
- levels=1:2
:目录层级结构
- keys_zone=my_cache:10m
:共享内存区域名称和大小
- inactive=60m
:60分钟内未被访问的缓存将被删除
- use_temp_path=off
:禁用临时路径
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_cache my_cache; # 使用前面定义的缓存区域
# 缓存有效条件
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 其他代理设置...
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_key "$scheme$request_method$host$request_uri$is_args$args";
# 当请求头中有Cache-Control: no-cache时绕过缓存
proxy_cache_bypass $http_cache_control;
# 当请求方法是POST时绕过缓存
proxy_cache_bypass $request_method = POST;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_revalidate on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m max_size=1g use_temp_path=off;
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_bypass $http_pragma $http_authorization;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
add_header X-Proxy-Cache $upstream_cache_status;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
验证缓存是否工作:
X-Proxy-Cache
字段HIT
, MISS
, BYPASS
, EXPIRED
等清除缓存:
rm -rf /var/cache/nginx/*
ngx_cache_purge
监控缓存:
nginx -T
检查配置du -sh /var/cache/nginx
strace
或lsof
监控文件操作keys_zone
大小proxy_cache_min_uses
减少磁盘I/Oproxy_cache_lock
防止缓存击穿通过合理配置Nginx反向代理缓存,可以显著提高网站性能,减轻后端服务器压力。