Varnish – Cookie

cacheconfigurationvarnish

I have the following situation:

On my site, javascript sets a cookie that contains relevant information for generating the markup.

I therefore want Varnish to cache each page separately for each value of said cookie.

All the documentation I have found says that Varnish will not cache if any cookie is present, and explains how to remove cookies in Varnish preprocessing.

This is obviously not what I want, I want to cache, even if a certain cookie is present, but seperately for each value of the cookie.

Any way to achieve this?

Best Answer

This is possible

For example:

sub vcl_recv {
        set req.http.X-COOKIEHASH = "";
        if (req.http.Cookie ~ "COOKIEHASH=") {
                set req.http.X-COOKIEHASH = regsub(req.http.Cookie,"^.*?COOKIEHASH=([^;]*);*.*$", "\1");
                /* to prevent default action when cookies are present */
                /* this is shortcut - you should adjust this to your VCL logic */
                return (lookup);
        }
}
sub vcl_hash {
        hash_data(req.http.X-COOKIEHASH);
}
sub vcl_miss {
        unset bereq.http.X-COOKIEHASH;
}
sub vcl_pass {
        unset bereq.http.X-COOKIEHASH;
}

In vcl_recv() we extract value for cookie (with the name COOKIEHASH) and in vcl_hash() we add this value to the hash function.

This is example for one cookie. But it's easy to add more cookie names. You must also remember to deal with other cookies (discard them or ignore).