You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Symfony应用配置Varnish并结合虚拟主机使用?

配置方案:让varnish-local.com通过Varnish访问Symfony应用

1. 修改Varnish监听端口

默认Varnish运行在6081,我们需要让它监听80端口,这样varnish-local.com的请求会直接到达Varnish,再由Varnish转发到Symfony的8000端口。

编辑Varnish启动配置

  • 针对Debian/Ubuntu系统,编辑/etc/default/varnish,修改端口参数:
    DAEMON_OPTS="-a :80 \
                 -f /etc/varnish/default.vcl \
                 -s malloc,256m"
    
  • 针对RHEL/CentOS系统,编辑/etc/varnish/varnish.params,修改:
    VARNISH_LISTEN_PORT=80
    
  • 若使用systemd服务,编辑/lib/systemd/system/varnish.service,调整ExecStart中的端口:
    ExecStart=/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl -s malloc,256m
    
  • 重启Varnish使配置生效:
    sudo systemctl restart varnish
    

2. 配置本地DNS解析

让varnish-local.com指向本地回环地址,确保本地请求能路由到Varnish:

  • 编辑/etc/hosts文件,添加以下内容:
    127.0.0.1 varnish-local.com www.varnish-local.com
    

3. 调整Apache虚拟主机(可选)

由于你通过symfony serve直接启动Symfony在8000端口,原Apache虚拟主机已无需直接提供服务,可禁用避免端口冲突:

  • 禁用虚拟主机:
    sudo a2dissite your-virtual-host-filename.conf
    sudo systemctl reload apache2
    
  • 若需保留Apache服务,修改/etc/apache2/ports.conf,将Listen 80改为Listen 8080,同时更新虚拟主机文件的<VirtualHost *:80>为<VirtualHost *:8080>。

4. 验证配置

  • 启动Symfony应用:symfony serve
  • 访问http://varnish-local.com,通过浏览器开发者工具查看响应头,若出现X-Cache: MISS(首次访问)或X-Cache: HIT(重复访问),说明Varnish已生效。
  • 也可使用curl命令验证:
    curl -I http://varnish-local.com
    

5. 优化VCL配置(可选)

当前VCL仅处理基础缓存逻辑,可添加规则提升缓存效率:

vcl 4.1;
backend default {
    .host = "127.0.0.1";
    .port = "8000";
}

sub vcl_recv {
    # 仅缓存GET/HEAD请求
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    # 处理PURGE清理请求
    if (req.method == "PURGE") {
        return (purge);
    }

    # 移除不必要的请求头,提升缓存命中率(按需调整)
    unset req.http.Cookie;
    unset req.http.Cache-Control;
    unset req.http.Pragma;
}

sub vcl_backend_response {
    # 404/500错误不缓存
    if (beresp.status == 404 || beresp.status == 500) {
        set beresp.ttl = 0s;
        return (deliver);
    }

    # 设置默认缓存时长为5分钟
    set beresp.ttl = 5m;

    # 移除响应中的Set-Cookie,避免缓存失效(按需调整)
    unset beresp.http.Set-Cookie;
}

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
        set resp.http.X-Cache-Hits = obj.hits;
    } else {
        set resp.http.X-Cache = "MISS";
    }
}
  • 重启Varnish加载新配置:
    sudo systemctl restart varnish
    

内容的提问来源于stack exchange,提问作者Chaitya Panchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:08:15