[Varnish 4] How to purge based on regex

Viktor Gunnarson viktor.gunnarson at ericsson.com
Wed Oct 29 09:09:53 CET 2014


Replying to my own message. After some more research I realized that what I really want to do is to set a ban. I hadn't realized that this actually allows Varnish to fetch new content and add it to the cache, my understanding was that a ban would force Varnish to _always_ go to the backend for objects matching the ban.

This is what I have added to my VCL:

if (req.method == "BAN") {
        if (!client.ip ~ purge) {
                return(synth(403, "Not allowed"));
        }

        #Add the ban
        ban("obj.http.x-url ~ " + req.http.X-Ban);

        return(synth(200, "Ban added"));
    }

Best regards,
Viktor

From: varnish-misc-bounces+viktor.gunnarson=ericsson.com at varnish-cache.org [mailto:varnish-misc-bounces+viktor.gunnarson=ericsson.com at varnish-cache.org] On Behalf Of Viktor Gunnarson
Sent: den 28 oktober 2014 12:18
To: varnish-misc at varnish-cache.org
Subject: [Varnish 4] How to purge based on regex

Hi,

I wonder how I can make Varnish 4 purge based on a regex? I've found old examples on how to do this in previous versions of Varnish but no example for Varnish 4.

What I want to accomplish is basically this:

I send a PURGE request:

PURGE /api/news/ HTTP/1.1

This should then purge /api/news/ but also all url's with query parameters (such as /api/news/?lang=en). I have tried the following without any success:

sub vcl_recv {
    if (req.method == "PURGE") {
        return (purge);
    }
}

sub vcl_hash {
    if (req.method == "PURGE") {

        #Remove ? and everything after that
        set req.http.purge-url = regsub(req.url, "^([/a-zA-Z0-9]*)([\?=&a-zA-Z0-9]*)", "\1" );

        #Make sure the url ends with a /
        if(!req.http.purge-url ~ "[.]*/$"){
            set req.http.purge-url = regsub(req.http.purge-url, "$", "/");
        }

        #Make it a regex
        set req.http.purge-url = "^" + req.http.purge-url + ".*$";

        hash_data(req.http.purge-url);

        return (lookup);
    }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.varnish-cache.org/lists/pipermail/varnish-misc/attachments/20141029/502c535c/attachment-0001.html>


More information about the varnish-misc mailing list