CakePHP和.htaccess资产缓存

时间:2011-10-21 16:34:25

标签: .htaccess caching cakephp

我仍然是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" />

所以它不会像我希望的那样工作。实现资产缓存的最佳方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:4)

添加查询字符串实际上与更改网址相同,浏览器会将其视为不同并重新加载资源,无论是CSS,图片还是其他任何内容。

答案 1 :(得分:1)

第1步:将您的webroot .htacess更改为此

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

第2步:sudo a2enmod到期

第3步:sudo service apache2 restart

第四步:喝啤酒,生活很美好。