Hacker News new | ask | show | jobs
by samarudge 4185 days ago
Varnish also supports custom cache keys via the VCL function `vcl_hash` as documented in https://www.varnish-software.com/static/book/VCL_functions.h...

I couldn't (quickly) find documentation on how to get the value of a specific cookie, but the server could send a user ID in a header or something Varnish can easily access to be used in the above function.

2 comments

Off the top of my head:

    sub vcl_recv {
      set req.http.X-Custom-Cookie-Value = regsub(req.http.cookie, ".*;|^)YOUR_COOKIE_NAME=([^;]+)(;.*|$)", "\2");
    }
Then you can just:

    sub vcl_hash {
      set req.hash += req.http.X-Custom-Cookie-Value;
    }
And now you're cache segmented on that cookie value.
You will probably have to write a VCL plugin if you want to parse the cookie, but that's not a huge hassle.
You can handle cookies in pure VCL – the code's not particularly elegant but it's manageable for light usage:

https://www.varnish-cache.org/trac/wiki/VCLExampleRemovingSo...

I'm not sure whether I would call "munging the cookie header with regexps" "cookie handling" ;).
Agreed – it's possible and for simple tasks such as stripping an analytics cookie it's workable but for anything more serious you'd want something like https://github.com/lkarsten/libvmod-cookie