仅基于主机使用 Varnish 进行缓存

Cache with Varnish based on host only

我想将 cookie 传递到后端,但我不想将它们添加到哈希 table。我的目标是仅根据主机为每个请求提供服务。可能吗?

如果未设置主机 header,默认情况下基于 url 和主机或 ip 的 varnish 缓存 - 参见 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);
}

如果您不在 vcl_recv 函数中取消设置 cookie,则默认情况下 varnish 不会缓存响应,因为它将 "return (pass);" 在 built-in vcl_recv 函数中.

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

如果你不想缓存那么这就可以了。

如果您确实想要缓存并需要将 cookie 发送到后端,那么我想您必须 "return (hash);" 在您的 "vcl_recv" 版本中,但这只有在响应是无论发送何种 cookie,始终相同。

附带说明:如果您确实想要缓存响应,那么您还需要取消设置后端设置的 Cookie 或避免进入 built-in "vcl_backend_response"

为了将 cookie 传递到后端并缓存请求,我这样做了:

  1. 从 vcl_recv 中删除:

    if (req.http.Authorization || req.http.Cookie) {
    /* Not cacheable by default */
        return (pass);
    }
    
  2. 将此添加到 vcl_fetch:

     unset beresp.http.set-cookie;