How to disable Varnish Cache from within a PHP scr

2019-08-12 07:50发布

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;
        }
}

标签: php varnish
4条回答
霸刀☆藐视天下
2楼-- · 2019-08-12 08:41

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楼-- · 2019-08-12 08:45

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

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

查看更多
姐就是有狂的资本
4楼-- · 2019-08-12 08:51

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

查看更多
\"骚年 ilove
5楼-- · 2019-08-12 08:53

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"

查看更多
登录 后发表回答