优化开发服务器静态资源加载:router.php 注入缓存头

为 JS/CSS/图片/字体等静态资源添加 ETag、Last-Modified、Cache-Control 响应头,
支持 304 Not Modified,避免浏览器每次完整重新下载。其余文件走原有逻辑。
This commit is contained in:
augushong
2026-05-24 11:53:46 +08:00
parent 577ee6b974
commit 646580e6dc

View File

@@ -1,7 +1,76 @@
<?php
// $Id$
if (is_file($_SERVER["DOCUMENT_ROOT"] . $_SERVER["SCRIPT_NAME"])) {
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$file = $_SERVER["DOCUMENT_ROOT"] . $uri;
if (is_file($file)) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
// 仅对真正的静态资源注入缓存头,其余走原逻辑
$cacheExts = [
'js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'webp',
'woff', 'woff2', 'ttf', 'eot', 'otf', 'map',
'json', 'xml', 'pdf', 'zip', 'mp3', 'mp4', 'wav', 'avi',
];
if (in_array($ext, $cacheExts)) {
$realPath = realpath($file);
$docRoot = realpath($_SERVER["DOCUMENT_ROOT"]);
// 路径穿越防护
if ($realPath === false || !str_starts_with($realPath, $docRoot)) {
http_response_code(403);
exit;
}
$etag = '"' . filemtime($file) . '-' . filesize($file) . '"';
// 304 Not Modified
if (
(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) ||
(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file))
) {
http_response_code(304);
exit;
}
header('ETag: ' . $etag);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT');
header('Cache-Control: public, max-age=86400');
header('X-Content-Type-Options: nosniff');
$mimeMap = [
'js' => 'application/javascript',
'css' => 'text/css',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'ico' => 'image/x-icon',
'webp' => 'image/webp',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'eot' => 'application/vnd.ms-fontobject',
'otf' => 'font/otf',
'map' => 'application/json',
'json' => 'application/json',
'xml' => 'application/xml',
'pdf' => 'application/pdf',
'zip' => 'application/zip',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'wav' => 'audio/wav',
'avi' => 'video/x-msvideo',
];
header('Content-Type: ' . ($mimeMap[$ext] ?? 'application/octet-stream'));
readfile($file);
exit;
}
// PHP、HTML 等文件交给 PHP 内置服务器处理
return false;
} else {
require __DIR__ . "/index.php";