简体   繁体   English

如何在Varnish上缓存对象,但告诉客户端不要缓存它

[英]How to cache an object on Varnish, but tell the client not the cache it

I am caching the product details page on Varnish, and then I purge the cache from the backend server whenever the product is updated. 我在Varnish上缓存产品详细信息页面,然后每当产品更新时就从后端服务器清除缓存。 I want my clients to never cache this page on their side, but always ask from Varnish, so that I can serve them the most recent copy. 我希望我的客户永远不要在他们这边缓存此页面,而总是向Varnish询问,以便为他们提供最新的副本。

Currently, I have the below config for vcl_backend_response: 当前,我具有以下vcl_backend_response的配置:

sub vcl_backend_response {
    unset beresp.http.Set-Cookie;
    #unset beresp.http.Cache-Control;
    #set beresp.http.Cache-Control = "no-cache";

    if (bereq.url ~ "^/products/\d+/details") {
        set beresp.ttl = 1h;
    }
}

But, using this config, client caches the response for 1 hour, and does not ask again, even the cache is purged on Varnish. 但是,使用此配置,客户端会将响应缓存1小时,并且不会再次询问,即使缓存是在Varnish上清除的。

If I uncomment the cache-control related lines, this time Varnish does not cache the page and always asks for a fresh copy from the backend server. 如果我取消对与缓存控件相关的行的注释,这次Varnish不会缓存页面,而是始终要求后端服务器提供新副本。

Is this achievable in Varnish v6.0? 这在Varnish v6.0中可以实现吗?

Yes, it's possible: 是的,有可能:

  • Define the logic for how long things are cached by Varnish inside the vcl_backend_response . vcl_backend_response内定义Varnish将内容缓存多长时间的逻辑。
  • Define the logic for how long things are cached by browser cache inside the vcl_deliver . vcl_deliver内定义浏览器缓存将内容缓存多长时间的逻辑。

So clients (browsers) can be instructed to cache with a different TTL than Varnish. 因此,可以指示客户端(浏览器)使用与Varnish不同的TTL缓存。 The following will ensure that browsers will not cache response: 以下内容将确保浏览器不会缓存响应:

sub vcl_deliver {
    set resp.http.Pragma = "no-cache";
    set resp.http.Expires = "-1";
    set resp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0";
}

Moreover, if you can modify your app, you can resort to a much finer approach outlined in first solution here , that is sending a single Cache-Control header which defines caching TTL for shared caches (Varnish) and private caches (browser) differently: 此外,如果可以修改应用程序,则可以采用此处第一个解决方案中概述的更精细的方法,即发送单个Cache-Control标头,以不同方式为共享缓存(Varnish)和私有缓存(浏览器)定义缓存TTL:

Cache-Control: s-maxage=31536000, max-age=86400

The header above will instruct a browser to cache resource for 86400 seconds, while Varnish will cache for 31536000. This is because s-maxage only applies to shared caches. 上面的标头将指示浏览器将资源缓存86400秒,而Varnish将缓存31536000。这是因为s-maxage仅适用于共享缓存。 Varnish evaluates it, while browsers don't. Varnish会评估它,而浏览器则不会。

尝试添加标题Cache-Control:无缓存,必须重新验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM