Configuring Varnish for Caching based on Cookies

Pinakee BIswas pinakee at waltzz.com
Tue May 24 11:13:13 CEST 2016


Hi Per Buer,

Thanks for the response and suggestion. I agree that caching with 
Cookies is a dangerous thing as cookies are mostly user specific and 
caching could leak them.

But the challenge here is that we have few cookies which would be needed 
by the backend. For example, we use a cookie which specifies the country 
for the client/user. The cookie is used by the backend  to figure out 
the country the user is in. But then I would like to cache the pages for 
a specific country. So, all the pages for users in US should be cached 
with a key using the country cookie - was trying this:

sub vcl_hash {
      if (req.http.cookie ~ "user_country=") {
         set req.http.X-TMP = regsub(req.http.cookie, 
".*user_country=([^;]+);.*", "\1");
         hash_data(req.http.X-TMP);
         unset req.http.X-TMP;
      }
}

I am not clear if unset strips the cookies so that they don't get cached 
or they are completely removed from the Cookie header before the request 
being passed to the backend. If it's former, it would be nice.

Any suggestion how to handle the above scenario would be great.

Thanks,

Pinakee

On 24/05/16 2:28 pm, Per Buer wrote:
>
>
> On Tue, May 24, 2016 at 10:46 AM, Pinakee BIswas <pinakee at waltzz.com 
> <mailto:pinakee at waltzz.com>> wrote:
>
>>     I am trying to set Varnish to cache content when login cookie is
>>     not present. Hence, I have modified the following subroutines:
>>
>
> What you want to do is to modify the request so the default VCL will 
> cache it rather than force Varnish to cache it. If you force Varnish 
> to cache it Varnish will end up caching it with cookies and such. This 
> is potentially dangerous.
>
> So I would recommend something like this in vcl_recv:
>
> if (req.http.cookie !~ "logged in") {
>     unset req.http.cookie; # strip the cookies - we don't need them
> }
>
>  # if there is a cookie here still the default policy will make sure 
> the request isn't cached.
>
>
>
> Per.
>
> -- 
> 	*Per Buer*
> CTO | Varnish Software AS
> Cell: +47 95839117
> We Make Websites Fly!
> www.varnish-software.com <https://www.varnish-software.com/>
>
>
> <http://info.varnish-software.com/signature>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.varnish-cache.org/lists/pipermail/varnish-misc/attachments/20160524/e973c6ad/attachment.html>


More information about the varnish-misc mailing list