2011-10-21 40 views
3

我仍然很新的CakePHP的時遇到了問題搞清楚如何優化資產緩存。的CakePHP和資產的.htaccess緩存

回來時,我在純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的「應用程序/配置/ core.php文件」的文件,可以使用下面這行代碼:

Configure::write('Asset.timestamp', 'force'); 

然而,這不僅使網址看起來像這樣:

<link rel="stylesheet" type="text/css" href="/css/style.css?1291314030" /> 

所以也沒有工作,我想它的方式。實現資產緩存的最佳方式是什麼?

謝謝!

+0

追加查詢字符串與更改url相同,瀏覽器會認爲不同並重新加載css。我一直在使用Flash內容做同樣的事情。 – grapefrukt

+0

是啊,我意識到我犯了一個錯誤,當我在做我的測試,它實際工作...哎呦!我應該刪除這個問題嗎? – Nick

+0

我會發佈一個正確的答案,它可以留在這裏供將來參考。 – grapefrukt

回答

4

追加查詢字符串實際上是相同更改網址,瀏覽器會認爲這是不同的,並重新加載的資產,無論是CSS,圖像或其他任何東西。

+0

是的,我意識到當我進行測試時我犯了一個錯誤,並且確實發揮作用......哎呀! – Nick

1

第1步:改變你的根目錄.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步:命令a2enmod到期

第3步:sudo的服務的Apache2重啓

步驟4:喝啤酒,生活很好。

+0

你真的值得一杯啤酒 –