How to invalidate a request in varnish which has a request param

157 Views Asked by At

I want to invalidate a request in Varnish from a java backend with HTTP headers. till now I am able to achieve cache arequest which does not have query param in it. Let's say I have a request: localhost:8090/api/data/abc?fields=test,test1 what headers do I need to set in this case for varnish to cache it.

I am able to ban a request which is like : localhost:8090/api/data/abc by using this headers for this request: request: localhost:8090/api/data/abc headers: responseHeaders.set("x-host", "localhost:8080"); responseHeaders.set("x-url", "/api/data/abc");

1

There are 1 best solutions below

0
On

VCL code

You can use the VCL example from the banning tutorial on the Varnish Developer Portal, which looks like this:

vcl 4.1;

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

sub vcl_recv {
    if (req.method == "BAN") {
        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;
}

Keep in mind that you need to add your backend definition and customize the values of the ACL.

Removing objects that match a specific query string pattern

Let's say the cache contains 4 objects identified by the following URL:

  • /?a=1
  • /?a=2
  • /?a=3
  • /?a=4

Imagine we want to remove the first 3. Assuming the value of the a query string parameter is a number, we can create the following HTTP request:

curl -XBAN -H"x-invalidate-pattern: ^/\?a=[1-3]+" http://localhost

As a result /?a=1, /?a=2 and /?a=3 will be removed from the cache, whereas /?a=4 is still stored in the cache.

Conclusion

The query string parameter is part of the URL. As long as you can match it in a regular expression, you can remove specific objects from the cache.