如何使用 Ban 表达式使清漆缓存对象无效

How to invalidate varnish cached object with Ban expression

考虑我请求的 url 是 www.example.com/foo/emplooyee?names = test1;test2。 varnish 存储整个 URL 以及查询参数以唯一标识缓存。

现在,在我的后端,我是 运行 一项服务,只要 names(即 test1 或test2) 应该用旧名称触发 HTTP 禁令(禁令表达式中一次一个名称)以使所有缓存的 URL 以相似的名称输入。

问题: 我的客户要求 url 可能是这样的,

如何编写 VCL 代码并在 Ban 表达式中使所有查询参数为 test1 的对象无效?

这是您需要禁止的 VCL 代码:

vcl 4.1;

acl purge {
    "localhost";
    "192.168.55.0"/24;
}

sub vcl_recv {
    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return(synth(405));
        }
        if(!req.http.x-invalidate-pattern) {
            return(purge);
        }
        ban("obj.http.x-url ~ " + req.http.x-invalidate-pattern
            + " && obj.http.x-host == " + req.http.host);
        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;
}

这是一个 HTTP 请求示例,用于使查询字符串中包含 test1 值的所有请求无效:

PURGE / HTTP/1.1
Host: www.example.com
X-Invalidate-Pattern: ^/foo/emplooyee\?names=([^;]+;)*test1(;[^;]+)*$

这是来自 curl 的相同请求:

curl -XPURGE -H'X-Invalidate-Pattern: ^/foo/emplooyee\?names=([^;]+;)*test1(;[^;]+)*$' http://www.example.com

此 VCL 片段可以灵活地通过禁止从缓存中删除多个项目,但如果您不通过 X-Invalidate-Pattern header 设置模式,它只会删除 URL本身来自缓存。

这是一个示例,我们只是从缓存中删除 http://www.example.com/foo/emplooyee?names=test1

curl -XPURGE 'http://www.example.com/foo/emplooyee?names=test1'

Don't forget to modify the acl block in the VCL code and add the right IP addresses or IP ranges.