Search code examples
cachingservervarnishvarnish-vcl

Cache with Varnish based on host only


I would like to pass cookies to the backend but I don't want them to be added to the hash table. My goal is to serve each request based on its host only. Is it possible?


Solution

  • By default varnish caches based on url and host or ip if the host header is not set - see built-in vcl_hash:

    sub vcl_hash {
        hash_data(req.url);
        if (req.http.host) {
            hash_data(req.http.host);
        } else {
            hash_data(server.ip);
        }
        return (lookup);
    }
    

    If you do not unset the cookies in the vcl_recv function then by default varnish does not cache the response as it will "return (pass);" in the built-in vcl_recv function.

    sub vcl_recv {
      ...
        if (req.http.Authorization || req.http.Cookie) {
            /* Not cacheable by default */
            return (pass);
        }
        return (hash);
    }
    

    If you do not want to cache then this would be fine.

    If you do want to cache and need to sent the cookies to the backend then I guess you have to "return (hash);" in your version of "vcl_recv" but this would only make sense if the response is always the same irrespective of the cookies sent.

    As a side note: If you do want to cache the response then you will also need to unset the Cookies set by the backend or avoid to get into the built-in "vcl_backend_response"