【问题标题】:How to use mod_rewrite with Zend Framework?如何在 Zend 框架中使用 mod_rewrite?
【发布时间】:2010-09-29 01:21:33
【问题描述】:
我刚刚使用 Zend Framework 部署了一个新站点。由于我的教程很受欢迎,我想将任何教程请求重定向到新站点上的相关页面。到目前为止,这就是我所拥有的:
重写前的网址:http://neranjara.org/tutorials/?tid=56
重写后的网址:http://neranjara.org/article/id/56
我尝试使用的 .htaccess 文件如下所示:
$ 猫 html/.htaccess
重写引擎开启
RewriteRule 教程/\?tid=(.*)$ /article/id/$1 [R=301]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php
但是这条规则不匹配任何 URL ... :'(
有人看到这里有问题吗?
【问题讨论】:
标签:
php
apache
zend-framework
mod-rewrite
【解决方案1】:
根据您之前的条目:
$ cat html/.htaccess
RewriteEngine on
RewriteRule tutorials/\?tid=(.*)$ /article/id/$1 [R=301]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php
我建议改用这个:
$ cat html/.htaccess
RewriteEngine on
RewriteCond %{QUERY_STRING} ^tid=([^&]*)
RewriteRule tutorials/ /article/id/%1 [R=301, L]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php [L]
顺便说一句,这只是在 mod_rewrite 中使用 QUERY_STRING 变量可以做的许多事情的一个例子。我的投票投给了“lpfavreau”,因为这是他们回答中的选项#2。
【解决方案2】:
查询字符串(传递给文件的参数)不会在 RewriteRule 中。
取自http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule:
模式将不匹配
针对查询字符串。相反,你
必须使用 RewriteCond 与
%{QUERY_STRING} 变量。你可以,
但是,在
替换字符串,包含一个
查询字符串部分。只需使用一个
替换里面的问号
字符串,表示以下
文本应重新注入
请求参数。当你想抹去
现有的查询字符串,结束
替换字符串只有一个
问号。组合新查询
旧字符串,使用 [QSA]
标志。
这里有两种可能:
-
删除您的第一个 RewriteRule 并在您的 index.php 中进行验证,然后再继续您的框架。初始查询应该在$_SERVER['REQUEST_URI'] 或类似的地方可用。所以验证它是否是 tutorials,取 tid 参数,然后继续重定向:
header("Location: http://http://neranjara.org/article/id/$id");
exit();
将 RewriteCond 与 %{QUERY_STRING} 一起使用,如 Apache 文档中所述。此解决方案在this one 之类的线程中进行了讨论。
// 编辑:
看看Chris' answer,他很友善地使用 QUERY_STRING 详细说明了解决方案。这可能是您想要使用的。谢谢克里斯。
【解决方案3】:
Zend 使用了 htaccess 可以提供的所有 htaccess 功能,因此有一个非常方便(可链接且有趣且没有很好的文档记录)的方法来在引导程序中实现这一点!
您必须在引导程序 (index.php) 中使用 Zend 路由器。可能是这样的:(这将是 foo.com/article/23
$路由器 =
$frontController->getRouter();
$route = 新的
Zend_Controller_Router_Route(
'文章/:id',
数组('id' => 1)); $router->addRoute('article', $route);
更多信息here