【问题标题】:Apache RewriteRule not rewriting as expectedApache RewriteRule 未按预期重写
【发布时间】:2013-11-02 09:08:51
【问题描述】:

你能看出以下 apache 重写规则有什么问题吗:

这是在我的 .htaccess 文件中的一个名为“text”的文件夹中,localhost/lombardpress 的子目录我有以下规则

Options +FollowSymlinks
RewriteEngine on
RewriteRule ([^/]+) /textdisplay.php?fs=$1 [NC]

我期待这个输入:

http://localhost/lombardpress-dev/text/lectio1

重写为:

http://localhost/lombardpress-dev/text/textdisplay?fs=lectio1

但是我得到了一个 404 错误。

在此服务器上找不到请求的 URL /textdisplay.php。

在我看来,RewriteRule 重写了地址,但不是我想要的 - 所以我的正则表达式一定有问题。

如果我能提供更多信息,请告诉我。

【问题讨论】:

  • 您应该使用 RewriteBase /lombardpress-dev/text/ 并从 /textdisplay.php?fs=$1 到 textdisplay.php?fs=$1 中删除第一个斜线
  • 我不熟悉 RewriteBase。你能写出那会是什么样子吗?

标签: .htaccess mod-rewrite


【解决方案1】:

试试这个

Options +FollowSymlinks
RewriteEngine on
RewriteBase /lombardpress-dev/text/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]+) textdisplay.php?fs=$1 [NC]

使用该重写条件,您不会再次将 textdisplay.php 重定向到自身。 问题是 [^/]+ 匹配除 / 之外的所有内容,因此它甚至匹配 textdisplay.php

【讨论】:

  • 所以这让我非常接近,但是,([^/]+) 只有在 write (le.*) 是否返回“lectio1”并且工作时才会返回“textdisplay.php”——非常奇怪的。我不明白为什么它应该匹配“textdisplay.php”,因为输入字符串中根本不存在“textdisplay.php”。
【解决方案2】:

去掉目标前面的/

RewriteRule ([^/.]+) textdisplay.php?fs=$1 [NC]
# no slash here ----^

【讨论】:

    【解决方案3】:

    删除目标 URL 中的前导斜杠:

    试试这个代码:

    Options +FollowSymlinks
    RewriteEngine on
    
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ textdisplay.php?fs=$1 [NC,L,QSA]
    

    参考:Apache mod_rewrite Introduction

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多