304:未修改和前端缓存 [英] 304: Not modified and front end caching
问题描述
我正在使用PHP脚本来提供文件。
我希望能够在我的http响应中发送一个 304
未修改的标头,如果该文件自客户端上次下载以来没有更改。这似乎是Apache(以及大多数其他Web服务器)的一个功能,但我不知道如何通过PHP实现这一功能。
I am using a PHP script to serve files.
I would like to be able to send back a 304
not modified header in my http response if the file has not changed since the client last downloaded it. This seems to be a feature in Apache (and most other web servers), but I have no clue how this can be implemented through PHP.
我听说过使用 $ _ SERVER ['HTTP_IF_MODIFIED_SINCE']
,但此变量似乎没有出现在我的 $ _ SERVER
超级数组中。
I have heard of using $_SERVER['HTTP_IF_MODIFIED_SINCE']
, but this variable does not seem to appear in my $_SERVER
super array.
我的问题不是如何返回 304
标题,而是如何知道应该返回一个。
My question is not how to return a 304
header, but how to know that one should be returned.
编辑:问题是我的 $ _ SERVER ['HTTP_IF_MODIFIED_SINCE']
未设置。这是我的 .htaccess
文件的内容:
The problem is that my $_SERVER['HTTP_IF_MODIFIED_SINCE']
is not set. This is the content of my .htaccess
file:
ExpiresActive On
ExpiresByType image/jpeg "modification plus 1 month"
ExpiresByType image/png "modification plus 1 month"
ExpiresByType image/gif "modification plus 1 month"
Header append Cache-Control: "must-revalidate"
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond $1 !^(controller\.php)
RewriteRule (.*\.jpg|.*\.png|.*\.gif) controller.php/$1
</IfModule>
HTTP_IF_MODIFIED_SINCE
仍未出现在 $ _ SERVER
超级数组。
HTTP_IF_MODIFIED_SINCE
still does not appear in the $_SERVER
super array.
推荐答案
HTTP_IF_MODIFIED_SINCE
是正确的方法。如果你没有得到它,请检查Apache是否有 mod_expires
和 mod_headers
启用并正常运行。借用对PHP.net的评论:
HTTP_IF_MODIFIED_SINCE
is the right way to do it. If you aren't getting it, check that Apache has mod_expires
and mod_headers
enabled and working properly. Borrowed from a comment on PHP.net:
$last_modified_time = filemtime($file);
$etag = md5_file($file);
// always send headers
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
// exit if not modified
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
@trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
// output data
这篇关于304:未修改和前端缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!