你需要两件事。
1) htaccess 规则处理
http://testurl.com/user/12345
http://testurl.com/user/12345/
http://testurl.com/user/12345/xxx
和相应规则避免重复内容(将旧格式/user.php?xxx重定向到新格式/user/ID/NAME)
为此,您可以将此代码放在您的根 htaccess 中
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} \s/user\.php\?id=([0-9]+)\s [NC]
RewriteRule ^ user/%1? [R=301,L]
RewriteCond %{THE_REQUEST} \s/user\.php\?id=([0-9]+)&name=([^&\s]+)\s [NC]
RewriteRule ^ user/%1/%2? [R=301,L]
RewriteRule ^user/([0-9]+)/?$ user.php?id=$1 [L]
RewriteRule ^user/([0-9]+)/([^/]+)$ user.php?id=$1&name=$2 [L]
注意:此时,请确保 mod_rewrite 已启用并且htaccess 允许(在 Apache 配置文件中)。
一个简单的测试:http://example.com/user/12345/XXXXX 应该在内部重写为/user.php?id=12345&name=XXXXX。
2) 现在你需要调整user.php 逻辑(这是你在这里检查你的数据<ID, NAME> 对是否存在)
<?php
if (!isset($_GET['id']) || empty($_GET['id']))
{
// error page not found (since there is no ID)
header("HTTP/1.1 404 Not Found");
return;
}
if (!isset($_GET['name']) || empty($_GET['name']))
{
// no name -> get it by its ID
$name = getNameByID($_GET['id']); // this function checks in the database
if ($name === NULL)
{
// error: ID is unknown -> page not found
header("HTTP/1.1 404 Not Found");
return;
}
// ID exists, we now have its name -> redirect to /user/ID/NAME (instead of /user/ID)
header("HTTP/1.1 301 Moved Permanently");
header("Location: /user/".$_GET['id']."/".$name);
return;
}
// if we reach here, we have an ID and a name in the url
// we have to check if NAME corresponds to ID (and if ID exists)
$name = getNameByID($_GET['id']); // this function checks in the database
if ($name === NULL)
{
// error: ID is unknown -> page not found
header("HTTP/1.1 404 Not Found");
return;
}
// now, check if NAME in the url corresponds to the one we got from database
if ($name !== $_GET['name'])
{
// it doesn't -> redirect to good NAME
header("HTTP/1.1 301 Moved Permanently");
header("Location: /user/".$_GET['id']."/".$name);
return;
}
// finally, here we're fine.
// do what you then have to do...
?>
我故意用“重复”部分编写这段代码,让您理解逻辑。
当然,你可以改进它。