在Nginx Proxy Manager中实现多级缓存可以显著提升网站性能,通常包含以下层级:
在NPM管理界面中:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g use_temp_path=off;
server {
# ... 其他配置 ...
location / {
proxy_cache STATIC;
proxy_cache_valid 200 1h;
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_cache_key "$scheme://$host$request_uri|$http_accept_encoding|$http_cookie";
添加清除缓存的端点(受限制访问):
location ~ /purge(/.*) {
allow 127.0.0.1;
allow YOUR_MANAGEMENT_IP;
deny all;
proxy_cache_purge STATIC "$scheme://$host$1|$http_accept_encoding|$http_cookie";
}
确保NPM发送正确的缓存头给CDN:
location / {
# ...
expires 1h;
add_header Cache-Control "public, no-transform";
add_header X-Accel-Expires $upstream_http_expires;
# ...
}
根据使用的CDN(如Cloudflare、AWS CloudFront等)添加特定头部:
add_header CDN-Cache-Control "max-age=3600";
add_header Edge-Control "cache-max-age=1h";
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Pragma "cache";
add_header Last-Modified "";
if_modified_since off;
}
# 动态内容 - 短缓存
location ~ \.php$ {
proxy_cache STATIC;
proxy_cache_valid 200 10s;
proxy_cache_bypass $http_cache_control;
proxy_no_cache $http_pragma $http_authorization;
}
# 静态内容 - 长缓存
location ~* \.(css|js|jpg|jpeg|png|gif|ico|cur|heic|webp|tif|tiff|mp3|m4a|aac|ogg|mid|midi|wav|mp4|m4v|webm|ogv|mov|flv|swf|svgz|eot|otf|woff|woff2|ttf|rss|atom|zip|tgz|gz|rar|bz2|7z|exe|doc*|xls*|ppt*|pdf)$ {
proxy_cache STATIC;
proxy_cache_valid 200 30d;
}
创建预热脚本:
#!/bin/bash
URLS=(
"/"
"/styles/main.css"
"/js/app.js"
"/images/logo.png"
)
for URL in "${URLS[@]}"; do
curl -s -o /dev/null "http://yourdomain.com${URL}"
done
location /cache-status {
allow 127.0.0.1;
allow YOUR_MANAGEMENT_IP;
deny all;
stub_status on;
access_log off;
}
在NPM的高级配置中添加:
log_format cache_log '$remote_addr - $upstream_cache_status [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/cache.log cache_log;
keys_zone
大小(每1MB约可存储8000个键)0 3 * * * find /var/cache/nginx -type f -mtime +30 -delete
通过以上配置,您可以在Nginx Proxy Manager中实现高效的多级缓存策略,显著提升网站性能和用户体验。