php - 如何使用 mod_rewrite 显示 SEO 友好的 URL?

标签 php mod-rewrite url-rewriting seo

我本质上不是 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/

相关文章:

php - SQL 查询在 phpMyAdmin 中正常,但在 PHP 代码中不起作用

javascript - 从 td :first row 获取数据字段

php - 数组推送,期望参数 1 为数组但给定为 null

php - 如何将特定目录中的所有重写 x.php 转换为 x.css?

wordpress - .htaccess 覆盖父 .htaccess

php - 将 PHP 变量插入 EloquentWhereRaw SQL 中

cakephp - 如何在显示为根目录的子目录中运行 CakePHP

apache - 子域的 .htaccess 端口重写

heroku - 如何在 Heroku 上为 Jekyll 静态站点创建别名?

c# - .NET 4 中的 URL 重写?