Varnish purge using HTTP and REGEX

风格不统一 提交于 2019-12-02 20:47:13

try this:

if varnish 3.0 and up.

vcl_recv {
    if (req.request == "PURGE") {
             if (!client.ip ~purge){
                     error 405 "Not allowed";
             }
     ban("req.http.host == " +req.http.host+" && req.url ~ "+req.url);
     error 200 "Ban added";

    }

Firstly define a whitelist of who can use the purge, then add the purger stanza in your VCL.

acl purge {
"127.0.0.1";
"10.22.0.0"/16;
}


sub vcl_recv {


if (req.http.X-Purge-Regex) {
        if (!client.ip ~ purge) {
            error 405 "Varnish says nope, not allowed.";
        }
        ban_url(req.http.X-Purge-Regex);
        error 200 "The URL has been Banned.";
}

Varnish will use the value of the header X-Purge-Regex to create a ban.

So then you can ban things like this:

curl -v -X PURGE -H 'X-Purge-Regex: ^/assets/*.css' varnishserver:6081

or

curl -v -X PURGE -H 'X-Purge-Regex: ^/images/*' varnishserver:6081

varnishserver is the address of your varnish server.

Sure there is.

In VCL you want to use the ban method - documented in "man vcl". It creates a filter on incoming requests. If you're going to use this at a rate of more than 2 times per second I recommend you google "ban luker friendly" and rewrite the expressions accordingly.

Untested code:

sub vcl_recv {
         if (req.method == "PURGERE" and client.ip ~ admin_network) {
            ban("req.http.host == " + req.http.host + " && req.url == " + req.url);
         }
acl purge {
"127.0.0.1";
}

sub vcl_recv {
    if (req.request == "PURGE") {
        if (!client.ip ~ purge) {
            error 405 "IP:" + client.ip + " Not allowed.";
        }
        ban("req.http.host == " + req.http.host + " && req.url ~ " + req.url);
        error 200 "host:" + req.http.host + " url:" + req.url + " Ban added";
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!