php - 重定向/.htaccess 以将旧的 PHP 参数 URL 更改为 SEO 友好的 CakePHP URL?

标签 php cakephp mod-rewrite seo

我即将更新我的网站以使用 CakePHP 而不是旧的自制框架。我需要编写 HTAccess 文件以将旧的 PHP 参数 URL 重定向到新的 CakePHP SEO 友好 URL,但我无法让它工作。

我的 htacess 文件(在 app/webroot 中的那个)现在看起来像这样:

RewriteEngine On

RewriteRule ^index.php?action=view&item=172$ index.php?url=item/172 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

这是行不通的。我尝试删除 L 并将其重定向到 item/172,但这也不起作用。当前的一个结束时未设置 URL 参数,如果我查看 $_SERVER['REQUEST_URI'] 它没有改变。虽然我不知道 mod_rewrite 是否会改变它。我的重写规则似乎没有激活,即使它是直接从我浏览器的 URL 栏复制的。我在没有和没有领先的 / 的情况下进行了尝试。没有骰子。

这是怎么回事?

我如何编写一个更通用的 URL 来进行转换?我试过类似的东西:

RewriteRule ^index.php?action=view&item=([0-9]+)$ index.php?url=items/$1 [R=301,L]    

但这也没有用。我做错了什么?

编辑 这真是令人愤怒。

RewriteRule ^(.*)$ /index.php?url=item/172 [R=301]

行得通。它将所有 url 汇集到正确形成的 Cake url 中。哪个蛋糕的处理器然后拿起并以某种方式处理。我不确定它是如何错过 Cake 的第二条重写规则的,但确实如此。试试这个:

RewriteRule ^(.*)$ item/172 [R=301]

返回格式错误的重定向,就像在前一个重定向中指定 last 一样:

RewriteRule ^(.*)$ /index.php?url=item/172 [R=301,L]

这表明它永远无法完成。

所以我其实很困惑为什么会这样:

RewriteRule ^(.*)$ /index.php?url=item/172 [R=301]

返回正确的 Cake url,但确实如此,并且它被发送到正确的页面。然而, 一旦我尝试更改第一部分,它就开始失败。

等一下。当它遇到 ? 时,它开始失败。它成功匹配 index.php 但不匹配 index.php? 但转义它没有任何区别。

RewriteRule ^index.php\?$ /index.php?url=item/172 [R=301]

无法匹配或返回正确的 URL。而且它似乎也不符合 Cake 的正常 catch all,因为 $_GET['url'] 是空的。您如何转义参数字符以在 mod_rewrite 中逐字匹配?

最佳答案

RewriteRule您只能测试 URI 路径而不能测试查询:

The Pattern will initially be matched against the part of the URL after the hostname and port, and before the query string. If you wish to match against the hostname, port, or query string, use a RewriteCond with the %{HTTP_HOST}, %{SERVER_PORT}, or %{QUERY_STRING} variables respectively.

所以:

RewriteCond %{QUERY_STRING} ^action=view&item=([0-9]+)$
RewriteRule ^index\.php$ /index.php?url=item/%1 [R=301,L]

关于php - 重定向/.htaccess 以将旧的 PHP 参数 URL 更改为 SEO 友好的 CakePHP URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007495/

相关文章:

php - 使用sql注入(inject)从其他数据库中选择SQL

regex - 如何从 OpenCart 3.0 上的所有链接中删除 route=

.htaccess - htaccess+modrewrite 问题

cakephp websocket Ratchet 安装错误

cakephp - 如何在 CakePHP 中编写跨多个表的联接查询?

linux - 为什么我的 .htaccess 文件在我的本地 MAMP 测试服务器上运行良好,但在我的 Linux 生产服务器上却不起作用?

php - 如何使用 jquery 或 php 打印月中特定日期

php - 如何在 javascript 和/或 php 中获取访问者的屏幕分辨率?

php - 如何在PHP中实现数字签名

mysql - 如何在按单个字段分组的列表中构建数组数组