通常,您希望在 Web 服务器中执行的代码尽可能小,因此为每个页面设置重写规则通常不是一个好主意。我建议在启用 SEO URL 时采用大多数 CMS 的工作方式:
将任何 url(mydomain/anytext.html
[实际上你也不应该使用 .html 扩展名])重写为脚本(例如mydomain.tld/translate.php
)
使用$_SERVER['PATH_INFO']
(应该包含anytext.html
)的内容来显示正确的页面
如果页面不存在,请设置正确的 HTTP 响应代码:(http_response_code(...)
有关 php5 5.4 以下的函数,请参阅此答案的结尾:PHP:如何发送 HTTP 响应代码?)
.htaccess 示例(实际上最初是“被盗”并从typo3 设置中严重修改)
RewriteEngine On
# Uncomment and modify line below if your script is not in web-root
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule (.*) translate.php$1 [L]
非常基本的类伪代码(未测试,可能存在语法错误)示例:
<?php
// using a database? you have to escape the string
$db = setup_db();
$page = db->escape_string(basename($_SERVER['PATH_INFO']));
$page = my_translate_query($page);
// no database? do something like this.
$trans = array( 'english' => 'italian', 'italian' => 'italian' );
$page = 'default-name-or-empty-string';
if(isset($_SERVER['PATH_INFO'])) {
if(isset($trans[basename($_SERVER['PATH_INFO'])])) {
$page = $trans[$trans[basename($_SERVER['PATH_INFO'])]];
}
else {
http_response_code(404);
exit();
}
}
// need to redirect to another script? use this (causes reload in browser)
header("Location: otherscript.php/$page");
// you could also include it (no reload), try something like this
$_SERVER['PATH_INFO'] = '/'.$page;
// you *may* have to modify other variables like $_SERVER['PHP_SELF']
// to point to the other script
include('otherscript.php');
?>
我在您的回答中看到您有另一个脚本 -dispatcher.php
您似乎不愿意修改。我相应地修改了我的回复,但请记住,到目前为止,最简单的方法是修改现有脚本以处理任何英文路径本身。