使用Apache关闭特定文件的缓存

时间:2015-07-09 11:33:36

标签: apache .htaccess caching

我在使用random() twig的网站上有一个页面,在Firefox和Chrome中,它被阻止工作,因为它会在页面加载后立即缓存。

有没有办法通过Apache配置关闭特定文件的缓存,让我们调用它default.html或者甚至更好地关闭该文件的脚本部分的缓存但是保持缓存图像文件?

我尝试了.htaccess,但这不起作用。

目前允许脚本工作的唯一方法是通过PHP标头关闭全局缓存:

<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>

但是因为我只需要关闭单个页面的缓存,所以关闭所有内容似乎都很疯狂。

1 个答案:

答案 0 :(得分:29)

想出来,定位特定文件(在本例中为index.php),将此代码添加到.htaccess的底部

<Files index.php>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>

或者定位特定的文件选择,即。我想缓存图片,但没有其他内容(匹配html, htm, js, css, php的文件不会被缓存):

<filesMatch "\.(html|htm|js|css|php)$">
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</filesMatch>

要检查.htaccess是否正在阅读,我在底部输入了几行垃圾,发现它没有被阅读,从htaccess重命名为.htaccess它起作用了。