【问题标题】:RewriteRule not working fine重写规则无法正常工作
【发布时间】:2012-02-05 02:36:37
【问题描述】:

我在.htaccess中写了以下规则

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)/$ profile.php?business=$1

当我输入网址时 http://www.abc.com/mujeeb/

页面已正确转移到个人资料页面,页面看起来很好。

但是我在 URL 中输入了这个 http://www.abc.com/mujeeb

页面不显示。

你能告诉我为什么吗?或者为此写规则?我尝试了很多次,但都没有成功。

穆吉布。

【问题讨论】:

标签: apache mod-rewrite


【解决方案1】:

page doesn't show. 因为您指定将 RewriteRule 应用于以 / 结尾的 URL。改写为

RewriteRule ^(.*)/?$ profile.php?business=$1 [L]

我希望你有额外的 RewriteCond 语句,以防止重定向的无限循环。

ps:基本上你可以通过两种方式防止循环

1) 检查请求的 url 是否与现有文件或目录不对应。这可能是最好的方法(将 cmets 读取到第二种方法)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ profile.php?business=$1 [L]

2) 检查您请求的不是来自 RewriteRule 的文件。这个方法不好,因为对于每一个请求,即使是已经存在的文件和目录,都会调用profile.php脚本

RewriteCond %{REQUEST_URI} !profile\.php$
RewriteRule ^(.*)/?$ profile.php?business=$1 [L]

【讨论】:

  • 没有。我在代码中没有条件。我应该写什么条件?
  • @Mujji 基本上你可以写两件事。让我更新一下我的答案 - cmets 不适用于代码清单 :)
【解决方案2】:

这是因为您使用 ^(.*)/$ 检查尾部斜杠。如果添加问号,则结尾的斜杠是可选的。

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)/?$ profile.php?business=$1

RewriteCond 是必要的,以确保规则只会被应用一次。否则 Apache 会陷入死循环。

【讨论】:

  • 当我按照你所说的设置规则时,页面现在没有加载。
  • 是的,您需要一个带有RewriteCond 的条件来避免这种情况。要么使用 Cheery 的方式,要么将我添加的条件添加到我的答案中。
【解决方案3】:

试试这个:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)[/]?$ profile.php?business=$1

这使得最后一个斜杠成为可选的。

【讨论】:

  • 没有理由将斜杠放在字符类中。
  • 对不起,我知道。习惯。而且我是 RegEx 的一个 n00b。
【解决方案4】:

您的规则是检查 URI 中的尾部斜杠,这就是 /mujeeb/ 有效但 /mujeeb 无效的原因。将您的代码更改为:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
# If the request is not for a valid file
#RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid directory
#RewriteCond %{REQUEST_FILENAME} !-f

# your rule without trailing slash
RewriteRule ^(.*)$ profile.php?business=$1 [L,QSA]

【讨论】:

    【解决方案5】:

    已经有很多好的答案了。我的答案有点不同。

    这是我通常做的。如果请求的 URL 不以 / 结尾,我会让浏览器重定向到带有尾随 / 的 URL。这与 Apache 的默认行为一致(由于 mod_dir)。所以,这就是我解决这个问题的方法。

    RewriteEngine On
    
    # Canonicalize http://example.com/mujeeb to http://example.com/mujeeb/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)([^/])$ /$1$2/ [R=307,L]
    
    # Let profile.php process http://example.com/mujeeb/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ profile.php?business=$1
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多