在宝塔面板中配置Nginx缓存:
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid 301 302 1m;
proxy_cache_valid any 1m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Proxy-Cache $upstream_cache_status;
}
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:100m inactive=24h
max_size=1g use_temp_path=off;
server {
# ...其他配置...
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
location / {
proxy_cache my_cache;
proxy_cache_revalidate on;
proxy_cache_min_uses 3;
proxy_cache_lock on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_valid 200 301 302 12h;
proxy_cache_valid 404 1m;
proxy_pass http://backend;
}
}
在宝塔面板中安装Varnish:
编辑/etc/varnish/default.vcl
文件:
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "80";
}
sub vcl_recv {
# 不缓存管理后台
if (req.url ~ "^/wp-admin" || req.url ~ "^/admin") {
return (pass);
}
# 不缓存POST请求
if (req.method == "POST") {
return (pass);
}
# 移除Cookie以提高缓存命中率
if (!(req.url ~ "^/wp-admin" || req.url ~ "^/wp-login.php")) {
unset req.http.cookie;
}
}
sub vcl_backend_response {
# 设置缓存时间
if (bereq.url ~ "\.(jpg|jpeg|png|gif|ico|css|js)$") {
set beresp.ttl = 30d;
} else {
set beresp.ttl = 1h;
}
# 不缓存设置Cookie的响应
if (beresp.http.Set-Cookie) {
set beresp.uncacheable = true;
set beresp.ttl = 120s;
return (deliver);
}
}
sub vcl_recv {
# 启用HTTP管道
if (req.http.connection ~ "(?i)close") {
set req.http.connection = "close";
}
# 处理压缩内容
if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
unset req.http.Accept-Encoding;
} elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
} elsif (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";
} else {
unset req.http.Accept-Encoding;
}
}
# 处理静态文件
if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|otf|ogg|ogm|opus|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
unset req.http.Cookie;
return (hash);
}
}
rm -rf /tmp/nginx_cache/*
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge my_cache "$scheme$request_method$host$1";
}
varnishadm "ban req.url ~ /"
varnishadm "ban req.url == /specific-page"
sub vcl_recv {
if (req.method == "PURGE") {
if (!client.ip ~ purge) {
return (synth(405, "Not allowed"));
}
return (purge);
}
}
add_header X-Cache-Status $upstream_cache_status;
grep -o "HIT\|MISS\|EXPIRED\|STALE" /var/log/nginx/access.log | sort | uniq -c
varnishstat
varnishlog
varnishstat -1 | grep -E "cache_hit|cache_miss"
分层缓存策略:
缓存分区:
缓存失效策略:
性能调优:
通过合理配置Nginx和Varnish缓存,可以显著提高网站性能,减少服务器负载,提升用户体验。