varnishvarnish-vclvarnish-4

Remove s-maxage from Cache-Control header using Varnish


We're currently using the s-maxage directive in the Cache-Control header from our origin to control the TTL in Varnish. However, I'd like to remove it from the response before delivery, so that no other caches in the request chain act on it.

I'm currently looking at the header VMOD, to remove s-maxage from the header, but leave the rest of it intact. I believe this could be achieved with something like this:

sub vcl_deliver {
    header.regsub(resp, "s-maxage=[0-9]+,?\s?", "")
}

As a newcomer to Varnish, I wanted to sanity-check this approach and make sure there isn't a better way to tackle it?

Appreciate any support or advice.


Solution

  • Replace header at delivery time

    The following VCL snippet will strip off the s-maxage attribute from the Cache-Control header before it is sent to the client.

    sub vcl_deliver {
        set resp.http.cache-control = regsub(resp.http.cache-control,
    "(,\s*s-maxage=[0-9]+\s*$)|(\s*s-maxage=[0-9]+\s*,)","");
    }
    

    Replace header at storage time

    It is also possible to strip off this attribute from the Cache-Control header before it gets stored into a cache object. In that case, you'll use the beresp.http.cache-control variable inside vcl_backend_response.

    sub vcl_backend_response {
        set beresp.http.cache-control = regsub(beresp.http.cache-control,
    "(,\s*s-maxage=[0-9]+\s*$)|(\s*s-maxage=[0-9]+\s*,)","");
    }
    

    Using vmod_headerplus

    If you're using Varnish Enterprise, you can use the vmod_headerplus module to easily delete header attributes:

    vcl 4.1;
    
    import headerplus;
    
    sub vcl_deliver {
        headerplus.init(resp);
        headerplus.attr_delete("Cache-Control","s-maxage",",");
        headerplus.write();
    }
    
    vcl 4.1;
    
    import headerplus;
    
    sub vcl_backend_response {
        headerplus.init(beresp);
        headerplus.attr_delete("Cache-Control","s-maxage",",");
        headerplus.write();
    }
    

    Although Varnish Enterprise is the commercial version of Varnish Cache, you can still use it without upfront license payments if you use it on AWS, Azure or GCP.