我需要设置一些 HTTP header “Expires”、“Cache-Control”、 “Last-Modified”,用于 CSS 文件、图像文件、js 文件等资源, 等(Webroot 内容)。
我读到有一些功能,通过
Configure::write('Asset.timestamp', true); // In core.php
和 Helper 类的 assetTimestamp 方法。
现在,问题是:如何使用它?
我阅读了 HtmlHelper 代码,在 css 方法中,第 361 行是这样的:
$url = $this->assetTimestamp($this->webroot($path));
最佳答案
已解决。
首先你要考虑通过Apache来做。你可以看看这个指南: http://httpd.apache.org/docs/2.2/caching.html
关键是 CakePHP 有一个方法可以做到这一点。而且非常好。
我将针对 CSS 文件进行解释。当然也可以用于JS内容。
1) 在您的 core.php 文件中(在 app/config/下)取消注释这一行:
Configure::write('Asset.filter.css', 'css.php');
该行告诉 CakePHP 通过该“css.php”脚本将所有请求路由到 CSS 文件。顾名思义,它是一个过滤器。在那里我们可以为所欲为。
2) 创建“css.php”文件。你必须在 app/webroot/下创建它
在那里,您可以获取浏览器请求的文件并应用一些缓存 HTTP header 。
类似于:
$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;
就是这样!在那里您的内容将与指定的 header 一起提供,浏览器将知道可以缓存它们。
看看:
http://www.bunchacode.com/programming/get-cakephp-build-in-css-compression-to-work/
有一个很好的 css.php 版本也可以压缩它。
关于php - 如何在 CakePHP2 中缓存静态内容(css、图像、js 文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6681869/