【发布时间】:2011-10-21 16:34:25
【问题描述】:
我对 CakePHP 还是很陌生,并且无法弄清楚如何优化资产缓存。
当我仍然使用纯 PHP 进行编码时,这就是我对 .htaccess 和 header.inc.php 文件的处理方式:
.htaccess:
<IfModule mod_rewrite.c>
# Turn the rewrite engine on
RewriteEngine On
# The following rewrite rule makes it so that if a URL such as
# http://example.com/css/style.1291314030.css is requested
# then it will actually load the following URL instead (if it exists):
#
# http://example.com/css/style.css
#
# This is to increase the efficiency of caching. See http://bit.ly/9ZMVL for
# more information.
RewriteCond %{DOCUMENT_ROOT}/$1/$2.$3 -f
RewriteRule ^(css|js)/(.*)\.[0-9]+\.(.*)$ /$1/$2.$3 [L]
</IfModule>
<IfModule mod_expires.c>
# Optimize caching - see http://yhoo.it/ahEkX9 for more information.
ExpiresActive On
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType application/x-javascript "access plus 1 year"
</IfModule>
header.inc.php:
foreach ($css_to_use as $current_css)
{
echo "\n\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/$current_css." . filemtime("{$_SERVER['DOCUMENT_ROOT']}/css/$current_css.css") . ".css\">";
}
此设置运行良好,因为当我在客户端网站上工作时,我不必告诉客户端执行硬刷新或清除其缓存;它是完全自动的,并且仍然具有缓存的好处。
我看到在 CakePHP 的“app/config/core.php”文件中,可以使用这行代码:
Configure::write('Asset.timestamp', 'force');
但是,这只会使 URL 看起来像这样:
<link rel="stylesheet" type="text/css" href="/css/style.css?1291314030" />
所以它不能按照我想要的方式工作。实现资产缓存的最佳方法是什么?
谢谢!
【问题讨论】:
-
附加一个查询字符串与更改 url 相同,浏览器会认为不同并重新加载 css。我一直对 Flash 内容做同样的事情。
-
是的,我意识到我在进行测试时犯了一个错误,并且它确实有效......哎呀!我应该删除这个问题吗?
-
我会发布一个正确的答案,它可以留在这里以供将来参考。