我需要设置一些 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 文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!