我在缓存方面遇到了问题...
我使用这个带有URL重写的PHP文件来压缩和缓存CSS和JS文件。
我原本以为,如果我更改/更新其中一个文件,那么浏览器将检索更新后的文件。但是,除非我清除缓存或刷新页面,否则它不会这样做。
我的代码有问题吗?还是浏览器只有在缓存过期后才能获取更新的内容?
<?php
$file = $_SERVER['DOCUMENT_ROOT'].'/'.$_GET['file'];
$last_modified_time = filemtime($file);
$etag = md5_file($file);
$expires = 60*60*24*7;
if(file_exists($file))
{
if($_SERVER['HTTP_IF_NONE_MATCH'] != $etag)
{
header("Pragma: public");
header("Cache-Control: maxage=$expires, must-revalidate");
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: \"{$etag}\"");
if($_GET['type'] == 'js') header('Content-type: application/javascript');
if($_GET['type'] == 'css') header('Content-type: text/css');
if($_GET['type'] == 'ico') header('Content-type: image/x-icon');
ob_start("ob_gzhandler");
include($file);
}
else {
header('HTTP/1.0 304 Not Modified');
}
}
else {
header("HTTP/1.0 404 Not Found");
}
?>
重写规则
RewriteRule ^(.*).js$ /compress.php?file=$1.js&type=js [L,QSA]
RewriteRule ^(.*).css$ /compress.php?file=$1.css&type=css [L,QSA]
RewriteRule ^(.*).ico$ /compress.php?file=$1.ico&type=ico [L,QSA]
---------
编辑:也许我应该用不同的方法来做这个?大公司使用什么来进行缓存,并如何在缓存过期之前强制浏览器获取更新的内容?
编辑 2:感谢大家的帮助。我选择了一个1小时的缓存时间。