【发布时间】:2014-11-16 10:25:57
【问题描述】:
我在重写 url 时遇到问题。我为自己编写了一个小框架,因为我的项目不需要一个包含很多东西的全尺寸框架。我定义了像 zend 框架这样的一般行为:
重写的url:域/控制器/动作
真实路径:domain/index.php?ctrl=controller&act=action
应该显示控制器和操作而不是 $_GET 命名键。在控制器和操作之后,如果我添加了无限数量的附加参数,则应将其添加为键/值,如下所示:
域/控制器/操作/key/value/key2/value2/key3/value3 ...
这是我的 .htaccess:
RewriteEngine On
RewriteBase /
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act=$2&$3=$4&$5=$6&$7=$8&$9=$10&$11=$12&$13=$14 [L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act=$2&$3=$4&$5=$6&$7=$8&$9=$10&$11=$12 [L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act=$2&$3=$4&$5=$6&$7=$8&$9=$10 [L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act=$2&$3=$4&$5=$6&$7=$8 [L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act2=$2&$3=$4&$5=$6 [L]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$ index.php?ctrl=$1&act=$2&$3=$4 [L]
RewriteRule ^([\w-]+)+/([\w-]+)?$ index.php?ctrl=$1&act=$2 [L]
RewriteRule ^([\w-]+)+/?$ index.php?ctrl=$1 [L]
页面只能通过控制器和动作调用。如果其中一个缺失,用户将被重定向。我为此设置了标题:
// Redirects
if (!isset($_GET) || !isset($_GET['ctrl'])) {
header('location: /index/index/');
}
if (!isset($_GET['act']) || (isset($_GET['act']) && empty($_GET['act']))) {
header("location: /".$_GET['ctrl']."/index/");
}
我知道它很脏。一般是可以的,但是有一些我无法解决的问题:
如果我尝试使用 domain/ 调用 webapp,页面将无法显示,或者我将通过搜索“domain/”重定向到 google。如果我输入域/控制器/操作,它就可以工作。
如果我在动作后添加一个斜杠,它会以 404 结束。它应该是相同的行为,就像没有斜杠结尾一样。
如果我在 header('location:...索引)。
但是如果我尝试 domain/ 它会导致 404。
前面没有斜线:
domain/controller/ 导致 domain/controller/controller/action 但 domain/ 将被正确重定向到 domain/index/index
我错过了什么? :(
谢谢
酪氨酸
【问题讨论】:
-
呃,请在您的 PHP 代码中解析 URL,然后简单地将所有请求转发到您的 PHP 文件,而不是使用如此丑陋的 URL……此外,简单地将查询字符串参数(包括它们的名称)映射到路径段中不会给你非常干净的网址...
-
我不知道你所说的“不是很干净”的网址是什么意思,但“domain/user/edit/id/3”对我来说看起来很干净
-
以本题的url为例。
http://stackoverflow.com/questions/25974343/mod-rewrite-problems-with-redirecting很好,但是对于您的系统,它将是例如http://stackoverflow.com/questions/id/25974343/title/mod-rewrite-problems-with-redirecting
标签: php apache .htaccess mod-rewrite redirect