【问题标题】:Varnish 4.0 multiple matchesVarnish 4.0 多重匹配
【发布时间】:2020-11-18 23:49:06
【问题描述】:

我需要同时为一个参数的多个特定值在 Varnish 中使缓存无效。现在代码按照这种模式进行调用:

varnish_host/path?.*parameter=1
varnish_host/path?.*parameter=2
varnish_host/path?.*parameter=3
varnish_host/path?.*parameter=4

按照此处https://kly.no/varnish/regex.txt 找到的 Varnish 2.0 文档,我找到了多重匹配的这条规则

Multiple matches
    req.url ~ "\.(jpg|jpeg|css|js)$"
    True if req.url ends with either "jpg", "jpeg", "css" or "js".

所以我改变了我的代码以通过以下方式适应它

varnish_host/path?.*parameter=(1|2|3|4)$

但它并没有按预期清理缓存,即使它返回状态 200。

Varnish 4.0 中是否有一种方法可以在参数中进行多重匹配?如果是这样,我们应该考虑的变化数量是否有限制?

【问题讨论】:

    标签: regex varnish vcl


    【解决方案1】:

    Varnish 不提供现成的基于 HTTP 的失效机制。

    你可以做的是issue bans using varnishadm。这将允许您设置匹配多个对象的正则表达式模式。

    Varnishadm 禁令示例

    这是一个这样的例子,我们将使 example.com 主机名的缓存中的每个 PNG 文件无效:

    varnishadm ban req.http.host == example.com '&&' req.url '~' '\\.png$'
    

    基于 HTTP 的禁止和清除

    varnishadm 工作正常,但集成到您的逻辑中并不容易。如果你想通过purgeban使缓存中的对象失效,你需要写一些VCL。

    这是一个有助于基于HTTP的失效的VCL sn-p:

    vcl 4.0;
    
    acl purge {
        "localhost";
        "192.168.55.0"/24;
    }
    
    sub vcl_recv {
        if (req.method == "PURGE") {
            if (!client.ip ~ purge) {
                return(synth(405, "Not allowed."));
            }
            if (!req.http.ban-url) {
                return(purge);
            }
            ban("obj.http.x-host == " + req.http.host + " && obj.http.x-url ~ " + req.http.ban-url);
            return(synth(200, "Ban added"));
        }
    }
    
    sub vcl_backend_response {
        set beresp.http.x-url = bereq.url;
        set beresp.http.x-host = bereq.http.host;
    }
    
    sub vcl_deliver {
        unset resp.http.x-url;
        unset resp.http.x-host;
    }
    

    重要提示:您需要调整ACL的值,这将禁止非法访问失效接口。您可以使用IP 地址IP 范围主机名 来限制访问。

    以下是我们如何通过 HTTP 执行相同的 PNG 失效:

    curl -XPURGE -H"ban-url: '\.png$'" http://example.com/
    

    您也可以只使单个 URL 无效:

    curl -XPURGE http://example.com/my-page
    

    因为上面的示例不包含 ban-url 请求标头,所以只有确切的 URL 无效,而不是模式开始匹配。

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 2014-06-16
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多