我需要一个PHP路由脚本,它使用具有许多重定向的现有htaccess文件,如:
Redirect 302 /some.ts http://targeturl/target.ts
我已经搜索了很多代码示例,但找不到一个合适的,我绝对是一个PHP初学者.它应该是PHP开发人员服务器的路由.
如果有人能在这里给我举个例子就好了.谢谢!
Update个
我现在有了第一次脚本try (在一些人工智能的帮助下):
<?php
// Get the requested URI
$requestURI = $_SERVER['REQUEST_URI'];
$filePath = __DIR__ . $requestURI;
/**
* Retrieves the redirect rules from the .htaccess file
*
* @return array
*/
function getHtaccessRedirectRules()
{
// Get the contents of the .htaccess file
$htaccessContent = file_get_contents('/www/.htaccess');
// Extract the redirect rules using a regular expression
$pattern = '/Redirect 302\s+(?P<expr>[^\s]+)\s+(?P<file>[^\s]+)/';
preg_match_all($pattern, $htaccessContent, $matches, PREG_SET_ORDER);
// Build an array of redirect rules
$redirectRules = [];
foreach ($matches as $match) {
$oldPage = str_replace('"', '', $match[1]);
$newPage = str_replace('"', '', $match[2]);
$redirectRules[$oldPage] = $newPage;
}
return $redirectRules;
}
// Check if the requested file exists
if (file_exists($filePath) && !is_dir($filePath)) {
// Serve the file directly
return false;
}
// Retrieve the redirect rules from the .htaccess file
$redirectRules = getHtaccessRedirectRules();
// Check if the requested URI matches any redirect rules
foreach ($redirectRules as $oldPage => $newPage) {
if ($requestURI === $oldPage) {
// Redirect to the new page
header("Location: $newPage", true, 302);
exit;
}
}
// If no redirect rule matches, serve a 404 page
http_response_code(404);
echo '404 Page Not Found';
?>
它仍然不起作用,但我用以下命令判断了正则表达式: https://www.phpliveregex.com/#tab-preg-match个
结果对我来说看起来还不错. 目前,我只收到来自PHP Dev服务器的"接受"和"关闭"消息.
也许其他人看到了一些问题(S).
谢谢!