Cookie based caching on Varnish 4.0

If you need to do Cookie-based caching on Varnish 4.0, for example caching content by country selection, this is what you need to do:

Let’s assume our cookie is named: selectedCountry. At first, in sub vcl_recv you have to add:


# Country based caching (cookie)
set req.http.X-COOKIEHASH = "";
if (req.http.Cookie ~ "selectedCountry=") {
set req.http.X-COOKIEHASH = regsub(req.http.Cookie,"^.*?selectedCountry=([^;]*);*.*$", "\1");
return (hash);
}
#

And on vcl_hash:

sub vcl_hash {
hash_data(req.http.X-COOKIEHASH);
}

This will ensure the cookie will pass along with the request. Please note that this is not a good idea for caching, but if you’re out of workarounds it may be a last resort solution.