4

Can someone explain the following vcl code:

sub vcl_hash {
    hash_data(req.url);

    if (req.http.host) {
      hash_data(req.http.host);
    } else {
      hash_data(server.ip);
    }

    if (req.http.Cookie) {
      hash_data(req.http.Cookie);
    }
}

I only understand the hashing of my req.url using hash_data function as the cache key. The next if else code is too vague for me.

danronmoon
  • 3,814
  • 5
  • 34
  • 56
John Roca
  • 1,204
  • 1
  • 14
  • 27

1 Answers1

7

The hash_data method is used to setup the hash, in other words the key, of the cached object. This key is used to compare the object with the objects already in cache.

In the code you post the first thing that is considered for the hash is the URL of the page requested: req.url.

But note that if Varnish used only the URL to hash an object it would be too vague and could lead to the same cache being delivered to different sites like www.example.com/test_url and www.example2.com/test_url.

In order to avoid this issue, it will add the host (req.http.host) to the hash if it exists, if not it will add the IP (server.ip) instead, e.g., http://192.168.0.1/test_url.

Lastly it will check for the existence of Cookies and add them to the hash as well if they do. This is done when the pages show different content based on cookies.

alejdg
  • 2,313
  • 21
  • 28