如何使用mod_rewrite显示SEO友好的URL?
我并不是一个PHP开发人员,我被要求在现有的PHP网站上执行一些SEO.
I am not a PHP developer at heart and I have been asked to perform some SEO on an existing PHP website.
我注意到的第一件事是丑陋的URL,所以我想让它们重写为更有用的信息.这是所有可能的模式:
The first thing I noticed was the ugly URLs so I want to get these to rewrite to something more informative. Here are all the possible patterns:
/index.php?m=ModuleType&categoryID=id
/index.php?m=ModuleType&categoryID=id&productID=id
/index.php?page=PageType
/index.php?page=PageType&detail=yes
所以基本上我想做的就是将它们转换为类似的东西:
So basically what I want to do is convert these into something like:
/ModuleType/Category
/ModuleType/Category/ProductName
/Page
/Page
在没有任何建议或示例之前,我还没有使用过mod_rewrite!
I haven't used mod_rewrite before any advice or examples would be great!
谢谢.
mod_rewrite 宁愿相反:将内部的/ModuleType/Category/ProductName
请求重写为/index.php?m=ModuleType&categoryID=id&productID=id
.在文档中使用新的URL是您应用程序的工作.
mod_rewrite would rather be used to do the opposite: rewrite requests of /ModuleType/Category/ProductName
internally to /index.php?m=ModuleType&categoryID=id&productID=id
. Using the new URLs in the documents is the job of your application.
编辑.以下是一个函数外观示例,该函数将参数化的URL转换为新的URL:
Edit Here’s an example of how a function might look like that turns your parameterized URLs into the new ones:
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>';