Files
2026-08-08 18:27:38 +08:00

57 lines
1.7 KiB
PHP

<?php
/**
* 本地调试用路由脚本(生产环境不使用,由 Nginx/Apache 处理)。
*
* 启动:php -S 127.0.0.1:8001 router.php
*
* 注意:内置服务器的 docroot 是项目根目录而非 public/,因此不能用
* `return false` 交还给内置服务器(那样会在项目根下找文件导致 404)。
* 这里直接读取 public/ 下的静态文件并附上正确的 MIME 类型。
*/
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '/');
$publicDir = __DIR__ . '/public';
// 防目录穿越
$realPublic = realpath($publicDir);
$staticPath = realpath($publicDir . $uri);
if (
$uri !== '/'
&& $staticPath !== false
&& is_file($staticPath)
&& str_starts_with($staticPath, $realPublic)
&& ! str_ends_with($staticPath, '.php')
) {
$mimeMap = [
'css' => 'text/css',
'js' => 'application/javascript',
'mjs' => 'application/javascript',
'json' => 'application/json',
'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',
'map' => 'application/json',
'txt' => 'text/plain',
'xml' => 'application/xml',
'pdf' => 'application/pdf',
];
$ext = strtolower(pathinfo($staticPath, PATHINFO_EXTENSION));
header('Content-Type: ' . ($mimeMap[$ext] ?? 'application/octet-stream'));
header('Content-Length: ' . filesize($staticPath));
header('Cache-Control: public, max-age=3600');
readfile($staticPath);
return true;
}
require $publicDir . '/index.php';