Varnish : how to add an exception for dynamic pages w/ cookies

cacheconfigurationvarnish

I would like to know what's the right way to avoid caching "some pages" of a website using Varnish and cache all the others.

This is what I have tried to do with the vcl conf:

     sub vcl_fetch {
         #set beresp.ttl = 1d;
         if (!(req.url ~ "/page1withauth") ||
             !(req.url ~ "/page2withauth")) {
            unset beresp.http.set-cookie;
         }
         if (!beresp.cacheable) {
             return (pass);
         }
         if (beresp.http.Set-Cookie) {
             return (pass);
         }
         return (deliver);
}

Thanks

Best Answer

Typically, this would be done in vcl_recv:

sub vcl_recv {
  if ( req.url !~ "^/page1withauth" && req.url !~ "^/page2withauth" )
  {
    unset req.http.Cookie;
    remove req.http.Cookie;
  }
}

Then, the only time you should have a set-cookie parameter coming back from the server is when you are trying to uniquely identify the connection. If it's because they just POSTed or similar, that's already going to evade the cache. If it's because you simply want to uniquely identify them, then the problem is your application's code intentionally breaking Varnish; fix your app if you can, otherwise you can override vcl_fetch similar to what you're doing here.