Nginx是一个高性能的HTTP服务器和反向代理服务器,通过配置反向代理缓存可以显著提高网站性能,减轻后端服务器负载。以下是详细的配置方法:
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
:定义共享内存区域名称和大小(10MB)
- inactive=60m
:60分钟内未被访问的缓存将被删除
- use_temp_path=off
:禁用临时路径
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server;
# 启用缓存
proxy_cache my_cache;
# 缓存有效状态码和时长
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 添加缓存状态头信息(用于调试)
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;
}
}
proxy_cache_key "$scheme$request_method$host$request_uri";
# 当请求包含特定cookie时不使用缓存
proxy_cache_bypass $cookie_nocache;
# 当请求参数包含nocache时不使用缓存
if ($arg_nocache) {
set $no_cache 1;
}
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_key "$uri$slice_range";
proxy_set_header Range $slice_range;
proxy_cache_valid 206 1h;
slice 1m;
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$is_args$args";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
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;
}
# 清除缓存接口(需要额外权限配置)
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge my_cache "$scheme$request_method$host$1$is_args$args";
}
}
}
查看缓存状态:
add_header X-Proxy-Cache $upstream_cache_status
查看缓存命中情况手动清除缓存:
rm -rf /var/cache/nginx/*
监控缓存:
# 查看缓存目录大小
du -sh /var/cache/nginx
# 查看缓存文件数量
find /var/cache/nginx -type f | wc -l
性能调优:
keys_zone
大小max_size
参数inactive
和valid
时间通过合理配置Nginx反向代理缓存,可以显著提高网站响应速度,降低后端服务器负载,特别是在处理静态内容或变化不频繁的动态内容时效果尤为明显。