server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
upstream backend {
server 192.168.1.100:8080 weight=5;
server 192.168.1.101:8080;
server 192.168.1.102:8080 backup;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_redirect off;
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_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
# 缓冲区设置
proxy_buffers 8 16k;
proxy_buffer_size 32k;
}
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
# 缓存键设置
proxy_cache_key "$scheme$request_method$host$request_uri";
# 缓存有效时间
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
# 缓存控制头
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:100m inactive=24h
max_size=1g use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
# 缓存锁定,防止多个请求同时更新缓存
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
# 缓存更新策略
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
# 缓存最小使用次数
proxy_cache_min_uses 3;
# 忽略客户端缓存控制头
proxy_ignore_headers Cache-Control Expires Set-Cookie;
}
# 不缓存特定路径
location /no-cache/ {
proxy_pass http://backend;
proxy_no_cache 1;
}
}
# 删除缓存目录
rm -rf /var/cache/nginx/*
# 然后重新加载Nginx
nginx -s reload
需要编译安装ngx_cache_purge模块。
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge my_cache "$scheme$request_method$host$1";
}
然后可以通过访问 http://example.com/purge/uri-to-purge
来清除特定URI的缓存。
可以使用如 nginx-cache-purge
等工具批量清除缓存。
$upstream_cache_status
监控缓存效果proxy_cache
指令是否配置正确Cache-Control
头阻止缓存proxy_cache_valid
设置是否合理max_size
参数限制缓存大小inactive
参数让不常用的缓存自动过期proxy_cache_bypass
指令强制更新特定请求通过合理配置Nginx的反向代理和缓存功能,可以显著提高网站性能和用户体验,同时减轻后端服务器的负载压力。