wiki:VCLExampleCacheCookies

Caching, even when cookies are present

Please note that this might quite easily end up serving content meant for one user to another, with all the chaos which can follow.

By default (and design) Varnish does not cache content with cookies in it. This is the recommended behaviour, so please only use the following receipe if you are sure you want to cache even with cookies and changing the web application is not possible.

Adding the cookie to the hash

This causes a lookup for a given object to include the Cookie. This will give you a per-user cache, so fairly low cache hit ratio and requires your system to not change the cookie on each page hit.

For a more granular approach, please use the recipe for caching content for logged in users

sub vcl_hash {
    hash_data(req.http.cookie);
}

Removing Set-Cookie from the backend (for a particular path)

In this case, we remove both the Cookie header and the Set-Cookie header for objects under a predefined path. This is quite common for images and similar static content.

sub vcl_recv {
    if (req.url ~ "^/images") {
        unset req.http.cookie;
    }
}

sub vcl_fetch {
    if (req.url ~ "^/images") {
        unset beresp.http.set-cookie;
    }
}

Caching based on file extensions

Here we throw away the cookie the client supplied by forcing a lookup. The default VCL code is _not_ run after vcl_recv.

sub vcl_recv {
 if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
    return(lookup);
 }
}

# strip the cookie before the image is inserted into cache.
sub vcl_fetch {
 if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
   unset beresp.http.set-cookie;
 }
}