通过 HTTP 标头或通过 url 中的 * 使清漆无效 清除网址禁止使用缓存标签禁止使用网址格式结论

问题描述

所以我有一些这样的网址 www.example.com/userID/productID 这个网址设置了这个 HTTP 标头 X-Cache-Tags: product-productID,user-userID,product

现在我想清除 X-Cache-Tagsproduct-productID 的所有缓存,或者我想清除所有 www.example.com/*/productID 的网址

这可能吗?

解决方法

这是实现它所需的 VCL 代码:

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));
        }
        if(!req.http.x-invalidate-tag && !req.http.x-invalidate-pattern) {
            return(purge);
        }
        if(req.http.x-invalidate-tag) {
            ban("obj.http.X-Cache-Tags ~ " + req.http.x-invalidate-tag);
        } else {
            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;
}

您可以通过 3 种方式使用此 VCL 从缓存中删除内容:

  1. 清除单个网址
  2. 禁止所有与缓存标签匹配的对象
  3. 禁止 URL 与模式匹配的所有对象

清除网址

当具有批准的客户端 IP 的请求执行 PURGE 请求时,仅使用确切的 URL 从缓存中删除对象:

curl -XPURGE http://example.com/20/100

禁止使用缓存标签

以下 curl 请求将从缓存中删除所有具有 X-Cache-Tags 响应标头且包含标记 product-10 的对象:

curl -XPURGE -H "x-invalidate-tag: product-10" http://example.com/

禁止使用网址格式

以下 curl 请求将从缓存中删除所有对象,对于产品 10,对于所有用户:

curl -XPURGE -H "x-invalidate-pattern: ^/[0-9]+/10/?$" http://example.com/

结论

只要你的 VCL 足够灵活,你就可以使用各种机制和规则来使缓存失效。

请通过 ACL 保护对内容失效的访问,如 VCL 示例中所述。您还可以添加额外的保护,例如密码身份验证或防火墙。