In this post, I'm going to describe how we can configure nginx to be able to cache responses based on the specific cookie value. 

Let's imagine a situation when you want to do an A/B test on your website, where 50% of users should see new headline text on the page. Other 50% of visitors will continue see the old page. In this case, all your server-side manipulation about splitting users to different versions will be ignored by nginx cache (of course, if you have it).

It happens because nginx, by default, has this configuration:

proxy_cache_key $scheme$proxy_host$request_uri;

So, it will use the same cache key for all users, who requests page with the same url.

Luckily, nginx allows us easily to customize proxy_cache_key! What we need to do, it's just to add a specific cookie to this key:

proxy_cache_key $scheme$proxy_host$request_uri$cookie_MY_COOKIE_NAME; 

And that's it! After this, if userA has MY_COOKIE_NAME=A and userB has MY_COOKIE_NAME=B they will receive different versions of page by the same url.


If you need more complex behaviour, where you won't use hardcoded cookie name in your nginx config, you can do something like this:

if ($http_cookie ~* "ab_(.*?)=([\w-]+)" ) {
  set $abcookie $1$2;
}

proxy_cache_key $scheme$proxy_host$request_uri$abcookie; 

As you can see, you can use $http_cookie and generate proxy_cache_key based on specific cookie patterns. In this concrete example we check if http cookies contains cookie with regex pattern "ab_(.*?)=([\w-]+)" and if this cookie exists, we generate new variable for proxy_cache_key.