proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m
inactive=60m use_temp_path=off max_size=1g;
请求处理阶段:
proxy_cache_methods
)proxy_cache_key
默认$scheme$proxy_host$request_uri
)缓存命中:
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
缓存未命中:
Cache-Control
、Expires
等)proxy_cache_bypass $http_cache_bypass; # 条件跳过缓存
proxy_no_cache $http_pragma $http_authorization; # 不缓存条件
proxy_cache_min_uses 3; # 至少请求3次才缓存
proxy_cache_lock on; # 缓存未命中时防止惊群效应
proxy_cache_key "$scheme$host$request_uri$cookie_user";
location /dynamic {
proxy_cache my_cache;
proxy_cache_valid 200 10s; # 短缓存周期
proxy_cache_use_stale updating;
proxy_cache_background_update on;
}
proxy_cache_key "$scheme$host$request_uri";
sub_filter '</body>' '<esi:include src="/user-profile" />';
sub_filter_once off;
基于时间失效:
proxy_cache_valid 200 302 5m;
主动清除:
# 安装ngx_cache_purge模块后
location ~ /purge(/.*) {
proxy_cache_purge my_cache "$scheme$host$1";
}
上游控制:
proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
proxy_cache_path /fast/ssd levels=1:2 keys_zone=hot:10m max_size=10g
inactive=1h use_temp_path=off;
proxy_cache_path /slow/hdd levels=1:2 keys_zone=cold:100m max_size=1t
inactive=30d use_temp_path=off;
map $request_method $cache_zone {
default "hot";
"GET" $is_args ? "hot" : "cold";
}
proxy_cache_path /cache levels=1:2 keys_zone=mycache:64m
inactive=24h max_size=10g loader_threshold=300
loader_files=200 loader_sleep=50ms;
log_format cache_log '$remote_addr - $upstream_cache_status [$time_local] '
'"$request" $status $body_bytes_sent';
access_log /var/log/nginx/cache.log cache_log;
缓存不生效:
proxy_cache_valid
配置Cache-Control: private/no-store
proxy_cache_bypass
条件缓存命中率低:
$upstream_cache_status
日志proxy_cache_min_uses
设置磁盘I/O过高:
proxy_temp_path
到高性能存储aio
和directio
指令通过合理配置Nginx缓存,可以显著降低服务器负载,提高响应速度,同时保持动态内容的实时性。