插件窝 干货文章 宝塔面板的缓存配置:Nginx、Varnish等

宝塔面板的缓存配置:Nginx、Varnish等

缓存 cache Nginx proxy 981    来源:    2025-04-18

宝塔面板缓存配置指南:Nginx与Varnish

Nginx缓存配置

1. 基本Nginx缓存配置

在宝塔面板中配置Nginx缓存:

  1. 登录宝塔面板,进入网站设置
  2. 选择"配置文件"选项
  3. 在http块中添加以下配置:
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
  1. 在server块中添加缓存规则:
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;
}

2. 高级Nginx缓存优化

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缓存配置

1. 安装Varnish

在宝塔面板中安装Varnish:

  1. 进入"软件商店"
  2. 搜索"Varnish"并安装
  3. 安装完成后,默认监听端口为6081

2. 基本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);
    }
}

3. 优化Varnish性能

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);
    }
}

缓存清理策略

Nginx缓存清理

  1. 手动清理:
rm -rf /tmp/nginx_cache/*
  1. 通过URL清理(需配置):
location ~ /purge(/.*) {
    allow 127.0.0.1;
    deny all;
    proxy_cache_purge my_cache "$scheme$request_method$host$1";
}

Varnish缓存清理

  1. 手动清理所有缓存:
varnishadm "ban req.url ~ /"
  1. 清理特定URL:
varnishadm "ban req.url == /specific-page"
  1. 通过HTTP PURGE方法(需在VCL中配置):
sub vcl_recv {
    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return (synth(405, "Not allowed"));
        }
        return (purge);
    }
}

监控与调试

Nginx缓存状态

  1. 添加缓存状态头:
add_header X-Cache-Status $upstream_cache_status;
  1. 查看命中率:
grep -o "HIT\|MISS\|EXPIRED\|STALE" /var/log/nginx/access.log | sort | uniq -c

Varnish监控

  1. 实时统计:
varnishstat
  1. 查看请求日志:
varnishlog
  1. 查看缓存命中率:
varnishstat -1 | grep -E "cache_hit|cache_miss"

最佳实践建议

  1. 分层缓存策略

    • 使用Varnish作为第一层缓存(内存)
    • Nginx作为第二层缓存(磁盘)
    • 结合CDN作为第三层缓存
  2. 缓存分区

    • 静态资源(图片/CSS/JS)设置长缓存时间(30天)
    • 动态内容设置短缓存时间(1-10分钟)
    • 个性化内容不缓存或设置极短缓存时间
  3. 缓存失效策略

    • 基于时间失效(TTL)
    • 基于事件失效(内容更新时主动清除)
    • 基于版本号(在URL中添加版本参数)
  4. 性能调优

    • 根据服务器内存调整缓存大小
    • 监控缓存命中率,保持在85%以上为佳
    • 对高流量网站考虑使用内存文件系统(如tmpfs)存储缓存

通过合理配置Nginx和Varnish缓存,可以显著提高网站性能,减少服务器负载,提升用户体验。