問題描述
我需要設置一些 HTTP 標頭Expires"、Cache-Control"、Last-Modified",用于資源如 CSS 文件、圖像文件、js 文件、等(Webroot 內容).
I need to set some HTTP headers "Expires", "Cache-Control", "Last-Modified", for resources as CSS files, Images files, js files, etc (Webroot content).
我了解到有一些功能,通過
I've read that there's some functionality, through
Configure::write('Asset.timestamp', true); // In core.php
和 Helper 類的 assetTimestamp 方法.
and the assetTimestamp method of the Helper class.
現在的問題是:它是如何使用的?
Now, the question is: How is it used?
我閱讀了 HtmlHelper 代碼,在 css 方法中,第 361 行是這樣的:
I read the HtmlHelper code and in the css method, line 361 there's this:
$url = $this->assetTimestamp($this->webroot($path));
推薦答案
已解決.
首先你要考慮通過Apache來實現.你可以看看這個指南:http://httpd.apache.org/docs/2.2/caching.html
First of all you have to consider to make it through Apache. You can take a look at this guide: http://httpd.apache.org/docs/2.2/caching.html
CakePHP 有一種方法可以做到這一點.而且還不錯.
The thing is that CakePHP has a method to do this. And is pretty good.
我將為 CSS 文件解釋這一點.當然也可以用于JS內容.
I'll explain this for CSS files. Of course can be used to JS content as well.
1) 在您的 core.php 文件中(在 app/config/下)取消注釋這一行:
1) In your core.php file (under app/config/) uncomment this line:
Configure::write('Asset.filter.css', 'css.php');
該行告訴 CakePHP 通過css.php"腳本將所有請求路由到 CSS 文件.顧名思義,它是一個過濾器.在那里我們可以為所欲為.
That line says to CakePHP to route all requests to CSS files through that "css.php" script. As the name implies, it's a filter. There we can do whatever we want.
2) 創建css.php"文件.您必須在 app/webroot/
2) Create that "css.php" file. You've to create it under app/webroot/
在那里,您可以獲取瀏覽器正在請求的文件并應用一些緩存 HTTP 標頭.
Make there, you can take the file that the browsen is requesting and apply some cache HTTP headers.
類似于:
$filepath = CSS . $regs[1]; //There are some variables that are can be used in this script, take a look to de docs.
$output = file_get_contents($filepath);
header("Date: " . date("D, j M Y G:i:s ", $templateModified) . 'GMT');
header("Content-Type: text/css");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + DAY) . " GMT"); //WEEK or MONTH are valid as well
header("Cache-Control: max-age=86400, must-revalidate"); // HTTP/1.1
header("Pragma: cache"); // HTTP/1.0
print $output;
就是這樣!在那里,您的內容將使用指定的標頭提供,瀏覽器將知道可以緩存它們.
That's it! There your content will be served with those headers specified and the browser will know that can cache them.
看看:
http://www.bunchacode.com/programming/get-cakephp-build-in-css-compression-to-work/
有一個很好的 css.php 版本,也可以簡化它.
There's a good version of css.php that also minfies it.
這篇關于如何在 CakePHP2 中緩存靜態內容(css、圖像、js 文件)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!