【发布时间】:2020-06-28 14:28:48
【问题描述】:
我有一个 API,我一直在尝试向它添加缓存控制标头。
API 已经使用PhpFastCache 进行服务器端缓存,但我想添加一个额外的浏览器控件缓存层。碰到this智能php缓存控制页面,稍作修改。
使用 PhpFastCache,我检查服务器端缓存是否存在,如果不存在则查询数据库并正常输出 200 响应代码。如果缓存确实存在,那么我执行以下操作:
//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);
//get a unique hash of this file (etag)
$etagFile = md5( $CachedString->get() );
//get the HTTP_IF_MODIFIED_SINCE header if set
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
//get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash)
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
//set last-modified header
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
//set etag-header
header("Etag: $etagFile");
//make sure caching is turned on
header('Cache-Control: public');
//check if page has changed. If not, send 304 and exit
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
header("HTTP/1.1 304 Not Modified");
exit;
}else{
//Cache Match - Output Cache Result
header('Content-Type: application/json');
echo $CachedString->get();
}
我正在使用这一行来获取缓存响应为 md5:
$etagFile = md5( $CachedString->get() );
然后检查一下这个 md5 内容是否发生了变化:
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
header("HTTP/1.1 304 Not Modified");
exit;
}else{
//Cache Match - Output Cache Result
header('Content-Type: application/json');
echo $CachedString->get();
}
但是,我似乎永远无法获得 304 响应标头。它总是一个 200 代码响应标头。
curl -I -L https://db.ygoprodeck.com/api/v7/cardinfo.php?name=Tornado%20Dragon
响应总是:
HTTP/1.1 200 OK
Date: Tue, 17 Mar 2020 13:37:31 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: __cfduid=daaab295934a2a8ef966c2c70fe0955b91584452250; expires=Thu, 16-Apr-20 13:37:30 GMT; path=/; domain=.ygoprodeck.com; HttpOnly; SameSite=Lax
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Cache-Control: public
Last-Modified: Tue, 17 Mar 2020 13:15:53 GMT
Etag: 399b9ba2d69ab115f46faa44be04d0ca
Vary: User-Agent
CF-Cache-Status: DYNAMIC
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 57571be8a986a72f-DUB
【问题讨论】:
标签: php caching browser-cache phpfastcache