如何缓存通过 PHP 返回的脚本

How to cache script returned via PHP

如果他被接受,我需要return给用户编写脚本。查用户时间太长,我要return 304 Not modified。我有简单的代码要检查,但它不起作用。浏览器不请求 If-Modified-Since。如果它是源 *.js 扩展,它可能是 script.js?ver=1.0 例如?但不是 *.php 是这样写还是有别的?

html代码:

<script src="get_secret_script.php"></script>

php代码:

$script_name = "./script.js";
$last_modified = filemtime($script_name);
$etag = hash_file('crc32b', $script_name);
header("Content-Type: text/javascript");

//header("Etag: $etag");

// Condition not met, there is no $_SERVER['HTTP_IF_MODIFIED_SINCE']
// in browser request
if(@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified)
{
    header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_modified) . " GMT", true, 304);  
    exit;
}

$fp = fopen($script_name, 'r'); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_modified) . " GMT", true, 200);
header("Content-Length: " . filesize($script_name));

fpassthru($fp); 
exit;

浏览器请求(不是第一个):

GET /test/get_secret_script.php HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
User-Agent: Browser identity string
Accept: */*
Referer: http://127.0.0.1/test/test.html
Accept-Encoding: gzip, deflate, br
Accept-Language: ...

关于你的情况,我认为你可以在 htaccess 或服务器配置中应用一些重写规则: 例如:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase  /
    RewriteRule ^script.js get_secret_script.php[NC,L]
</IfModule>