我本质上不是 PHP 开发人员,我被要求在现有的 PHP 网站上执行一些 SEO。
我首先注意到的是丑陋的 URL,因此我想让这些 URL 重写为内容更丰富的内容。以下是所有可能的模式:
/index.php?m=ModuleType&categoryID=id
/index.php?m=ModuleType&categoryID=id&productID=id
/index.php?page=PageType
/index.php?page=PageType&detail=yes
所以基本上我想做的是将这些转换成类似的东西:
/ModuleType/Category
/ModuleType/Category/ProductName
/Page
/Page
在任何建议或示例都很棒之前,我还没有使用过 mod_rewrite!
谢谢。
最佳答案
mod_rewrite宁愿用来做相反的事情:在内部将 /ModuleType/Category/ProductName
的请求重写为 /index.php?m=ModuleType&categoryID=id&productID=id
。使用文档中的新 URL 是您应用程序的工作。
编辑 下面是一个将参数化网址转换为新网址的函数示例:
function url($url, $rules) {
$url = parse_url($url);
parse_str($url['query'], $url['query']);
$argNames = array_keys($url['query']);
foreach ($rules as $rule) {
if ($rule[0] == $url['path'] && array_keys($rule[1]) == $argNames) {
$newUrl = $rule[2];
foreach ($rule[1] as $name => $pattern) {
if (!preg_match('/'.addcslashes($pattern, '/').'/', $url['query'][$name], $match)) {
continue 2;
}
$newUrl = str_replace('<'.$name.'>', $match[0], $newUrl);
}
return $newUrl;
}
}
return $url;
}
$rules = array(
array(
'/index.php',
array('m'=>'.*', 'categoryID'=>'.*', 'productID'=>'.*'),
'/<m>/<categoryID>/<productID>'
)
);
echo '<a href="' . url('/index.php?m=ModuleType&categoryID=categoryID&productID=productID', $rules) . '">/ModuleType/Category/ProductName</a>';
关于php - 如何使用 mod_rewrite 显示 SEO 友好的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513311/