Some of my clients use Varnish for caching on their sites, while others rely on Nginx. Due to the fact that their sites must be highly dynamic, yet quick to load, I need to configure both systems (Varnish and Nginx) to use dynamic cache keys.

To be clearer, I know that, out of the box, both of them use the page URL as the cache key. That is, they take http://example.org/some/page as the key and store a cached copy of that page. When the same URL is requested again, the cached page is returned. This way, there is only one copy of the content for each URL.

What I need to do is change this behaviour, so that the Varnish and/or Nginx use a cache key that does not just contain the URL, but also some values that can be found in cookies. In pseudo code, the logic would have to be the following:

$cookies = ["one", "two", "three"]

if(<none of the cookies is set>) {
  // Cookies are not set
  // Let the page load dynamically, so that cookies can be set
else {
  // Cookies are set
  // Create a dynamic cache key, taking the cookies into account
  $cache_key = $page_url + $cookies["one"] + $cookies["two"] + $cookies["three"]

I looked for such a solution, but I barely know Varnish and Nginx and I could not find an example of how that could be achieved. Any suggestion, or link to examples, would be welcome. Thanks in advance for the help.

  • 1
    – Alexey Ten
    Aug 27, 2015 at 19:06
  • Thanks for the link. It doesn't look like it's possible to add conditional logic in Nginx, or am I mistaken?
    – Diego
    Aug 28, 2015 at 17:10
  • Never mind, I think I found out how conditionals can be implemented. As I wrote, I barely know Nginx and Varnish, I have to go by trial and error. :)
    – Diego
    Aug 28, 2015 at 17:25


You must log in to answer this question.

Browse other questions tagged .