简体   繁体   English

如何设置http头缓存?

[英]How to set http header Cache?

I need to store the javascript and page details to browser cache using http headers. 我需要使用http标头将JavaScript和页面详细信息存储到浏览器缓存中。

Can anyone help me to get this? 谁能帮我得到这个?

Many thanks 非常感谢

You could use HTML meta: 您可以使用HTML meta:

<meta http-equiv="Cache-control" content="public">

or 要么

PHP headers: PHP标头:

header("Cache-Control: public"); // HTTP/1.1
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

Source: [PHP Manual] 资料来源: [PHP手册]

How about simply setting the expire date in a header - 仅在标题中设置到期日期如何-

header("Cache-Control: public");
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

It should be noted that modern browsers do a good job caching resources. 应当指出,现代浏览器在缓存资源方面做得很好。 Usually these methods are used to force reloading a resource; 通常,这些方法用于强制重新加载资源。 To prevent browser cache. 防止浏览器缓存。

I think there is some confusion about exactly what you are wanting to cache. 我认为对于您要缓存的内容有些困惑。 Two items are being referred to here - 这里提到两个项目-

  1. The page itself with all HTML elements and references to external files. 页面本身包含所有HTML元素和对外部文件的引用。
  2. A JavaScript file being referenced to by the HTML document. HTML文档引用的JavaScript文件。

To cache the first item (the page), setting the headers with PHP should cache the HTML contents of the page. 要缓存第一项(页面),请使用PHP设置标头应缓存页面的HTML内容。

header("Cache-Control: public");
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

This will cache the contents of the page but not necessarily the files referenced by it. 这将缓存页面的内容,但不一定缓存页面引用的文件。 For example, if you had in your HTML file this code - 例如,如果您的HTML文件中包含以下代码-

<script src="http://domain/some/js/file.js" type="javascript" ></script>

Then that text will be caches but not file.js . 然后,该文本将是缓存,而不是file.js To manually set the cache on those external files, you'll need to serve them using PHP and manually set the headers. 要在这些外部文件上手动设置缓存,您需要使用PHP为它们提供服务并手动设置标头。 You'll want to do something similar to this - 您将想要做类似的事情-

<script src="another_file.php" type="javascript" ></script>

Now in another_file.php you are going to want to load the JavaScript file and "echo" it out with the appropriate headers - 现在,在another_file.php您将要加载JavaScript文件并使用相应的标头“回显”它-

$file = '/absolute/path/to/your_script.js';
if (file_exists($file)) {
    header('Content-Type: text/javascript');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM