正则表达式将页面重定向到不需要的页面

时间:2013-07-25 14:22:05

标签: regex apache .htaccess url-rewriting

我使用htaccess来清理URL,以下是个人资料页面的规则

RewriteRule ^([0-9a-z]+)$ profile.php?user=$1

但我有其他网页,例如关注者,跟踪登录用户,他们可以在/followers页面看到他们的关注者,其规则是

RewriteRule ^following$ follow.php?follow=following
RewriteRule ^followers$ follow.php?follow=followers

但是当我转到/followers时,我会被重定向到profile.php(上面的第一条规则),因为您可以在第一个规则中看到域名localhost/text_that_comes_here转到{{1 }}

可能是什么解决方案,以便我的profile.php和其他网页可以正确重定向。

1 个答案:

答案 0 :(得分:1)

您应该在更通用的规则之前加入更具体的规则 在这种情况下,规则^following$^followers$^([0-9a-z]+)$ ...更具体 这将导致“跟随”和“关注者”被第一个规则^([0-9a-z]+)$捕获,因此重定向到profile.php

重新排序.htaccess如下所示:

RewriteRule ^following$ follow.php?follow=following
RewriteRule ^followers$ follow.php?follow=followers
RewriteRule ^([0-9a-z]+)$ profile.php?user=$1


编辑:回答您的评论,这是您可以用来以编程方式执行此操作的方法:
*但是,这是一种黑客行为,我不会将其作为永久修复。

由于它会重定向到profile.php?user=following(或profile.php?user=followers),您可以做的是在profile.php页面的开头添加条件并检查参数{{1} }(或“粉丝”)。 类似的东西:

$_GET["user"]="following"

这意味着您将无法拥有任何名为if ($_GET["user"]="following" || $_GET["user"]="followers") { $_GET["follow"]=$_GET["user"]; //set the parameter required in “follow.php” include("follow.php"); exit; } following的用户,这些用户无论如何都不会发生......但仍然存在。