How to disable Varnish Cache from within a PHP script?

懵懂的女人 提交于 2019-12-11 07:49:06

问题


I distribute a PHP script and recently a lot of people are having trouble with varnish cache on shared hosting accounts.

This is the code at the top of the PHP script. However I still get "Varnish: HIT" in response headers (and the script doesn't work correctly).

header('Pragma: no-cache');
header('Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate, proxy-revalidate');
header('Expires: Tue, 04 Sep 2012 05:32:29 GMT');

One hosting provider said it was impossible to disable varnish from within a PHP script, even by setting the cache headers like above. This seems .. well .. silly? But seems to match my experience.

So is there a way to disable/skip varnish from within PHP? Or does varnish (by default) just ignore these cache headers set by PHP?


Thanks Jens-André Koch - I'll include varnish instructions along with the PHP script to make it ignore no-cache responses:

sub vcl_fetch {
        if (beresp.http.cache-control ~ "(no-cache|private)" ||
            beresp.http.pragma ~ "no-cache") {
                set beresp.ttl = 0s;
        }
}

回答1:


You have to configure Varnish to avoid caching the page. Modify your VCL to detect the headers... specify your own header to turn caching off for your file or add it statically as non-cached to the config.

https://www.varnish-software.com/static/book/build/exercises/complete-avoid_caching_a_page.html?highlight=headers




回答2:


You cannot disable Varnish from within PHP but there is a trick you can use to make Varnish ignore the current page. Varnish will not be caching pages where you are setting a cookie, so whenever you want Varnish not cache a certain page you can write this piece of code:

setcookie('xx', microtime(true), time()+600, '/');

Not the most optimal solution, but it works just fine...




回答3:


You can disable Varnish cache creating an .htaccess file with the following:

Header set Cache-Control "max-age=0, private, no-cache, no-store, must-revalidate"




回答4:


As I understand situation, you can only do a purge of cache:

https://www.varnish-software.com/static/book/Cache_invalidation.html



来源:https://stackoverflow.com/questions/25954657/how-to-disable-varnish-cache-from-within-a-php-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!