【问题标题】:.htaccess - Redirect All URLs + Existing Directories to index.php.htaccess - 将所有 URL + 现有目录重定向到 index.php
【发布时间】:2019-11-29 22:40:13
【问题描述】:

我需要能够将目录中的所有 URL 绝对重定向到目录中的 index.php 文件。与我找到的所有其他答案不同,此包括现有目录和现有文件。我使用 Apache 和 .htaccess 文件来完成此操作。到目前为止我的 .htaccess 文件如下:

重写引擎开启 RewriteRule /sub/directory/index\.php - [L] RewriteRule - /sub/directory/index\.php

但由于某种原因,它不会将任何内容重定向到 index.php。我也试过:

重写引擎开启 RewriteRule /sub/directory/index\.php - [L] RewriteRule ^.*$ /sub/directory/index\.php

但这给了我一个不可避免的“500错误”。我究竟做错了什么?如何简单地将所有内容重定向到 index.php?

TIA

【问题讨论】:

    标签: php .htaccess mod-rewrite


    【解决方案1】:

    错误在于这个RewriteRule

    RewriteRule /sub/directory/index\.php - [L]
    

    What is matched?

    • 每个目录上下文(Directory 和 .htaccess) 中,Pattern 仅与部分路径匹配,例如“/app1/index.html”的请求>”可能会导致与“app1/index.html”或“index.html”进行比较,具体取决于 RewriteRule 的定义位置。

    和“每目录重写”:

    • 删除的前缀始终以斜杠结尾,这意味着匹配发生在从不具有前导斜杠的字符串中。因此,带有 ^/ 的模式在每个目录上下文中永远不会匹配

    这意味着,前导斜杠会阻止模式匹配。改成

    RewriteRule ^sub/directory/index\.php - [L]
    

    将解决问题。


    500 Internal server error 来自第二条规则(结合不匹配的第一条规则)。

    RewriteRule ^.*$ /sub/directory/index\.php
    

    这会将任何请求重写为/sub/directory/index.php,然后又将再次重写为/sub/directory/index.php,依此类推,直到重写模块放弃并显示“重定向过多”错误或类似错误。

    【讨论】:

    • 你是对的。那条线不匹配,导致问题!谢谢!也许我的问题并不清楚,但 .htaccess 文件实际上是 in '/sub/directory/' 文件夹。因此,一旦我将其简化为 RewriteRule ^index\.php - [L] 它就起作用了!
    【解决方案2】:

    仍然不知道为什么我的第二个原始 .htaccess 文件不起作用,但以下终于让它起作用了:

    重写引擎开启 RewriteCond %{REQUEST_URI} !=/sub/directory/index.php 重写规则 .* /sub/directory/index.php

    但是,我很乐意接受任何可以很好地解释为什么我的第二个原始文件一直给我 500 错误的答案。

    【讨论】:

      【解决方案3】:

      语法错误,另外在第二个匹配(不是最后一个)之后重新匹配第一个规则。

      任何请求 -> /sub/directory/index.php -> /sub/directory/index.php - [L]

      <IfModule mod_rewrite.c>
          RewriteEngine On
          # RewriteRule /sub/directory/index\.php - [L]
          RewriteRule ^(.*)$ /sub/directory/index.php [L]
      </IfModule>
      

      我的另一个建议(index.php是目录索引文件,在请求目录的时候排在第一位):

      <IfModule mod_rewrite.c>
          RewriteEngine On
          RewriteRule ^sub/directory/(.*)$ /sub/directory/ [R=301,L]
      </IfModule>
      

      【讨论】:

        【解决方案4】:

        另一种方式,您可以使用此代码:(注释第二行和第三行以接受 url 中的偶数文件和目录)

        重写引擎开启 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

        【讨论】:

          【解决方案5】:

          我遇到了同样的问题,我可以以某种方式解决它(我猜不是以聪明的方式)。 问题是因为 HTML 没有更改到根文件夹。

          我可以通过使用HTML“base tag”来解决我的问题(你可以根据你想要的根目录来适配路径。

          您还需要提供一个条件以仅在目标页面上允许此更改。

          【讨论】:

            猜你喜欢
            • 2016-11-30
            • 1970-01-01
            • 2012-04-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-08-26
            • 2016-11-30
            • 1970-01-01
            相关资源
            最近更新 更多