为了账号安全,请及时绑定邮箱和手机立即绑定

.htaccess - 将所有 URL + 现有目录重定向到 index.php

.htaccess - 将所有 URL + 现有目录重定向到 index.php

PHP
喵喵时光机 2021-10-22 14:18:44
我需要能够将目录中的所有 URL 重定向到目录中的 index.php 文件。与我找到的所有其他答案不同,这包括现有目录和现有文件。我正在使用带有 .htaccess 文件的 Apache 来完成此操作。到目前为止,我的 .htaccess 文件如下:<IfModule mod_rewrite.c>重写引擎开启RewriteRule /sub/directory/index\.php - [L]重写规则 - /sub/directory/index\.php</IfModule>但出于某种原因,它不会将任何内容重定向到 index.php。我也试过:<IfModule mod_rewrite.c>重写引擎开启RewriteRule /sub/directory/index\.php - [L]重写规则 ^.*$ /sub/directory/index\.php</IfModule>但这给了我一个不可避免的“500 错误”。我究竟做错了什么?如何简单地将所有内容重定向到 index.php?
查看完整描述

3 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

错误与此有关 RewriteRule

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

请参阅匹配什么?

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

和“每目录重写”:

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

这意味着,前导斜杠会阻止模式匹配。将其更改为

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

将解决问题。


500内部服务器错误来自于第二规则(在组合与非匹配的第一规则)。

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

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


查看完整回答
反对 回复 2021-10-22
?
四季花海

TA贡献1811条经验 获得超5个赞

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


    重写引擎开启

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    重写规则 ^(.*)$ /index.php?path=$1 [NC,L,QSA]


查看完整回答
反对 回复 2021-10-22
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

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


任何请求 -> /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>


查看完整回答
反对 回复 2021-10-22
  • 3 回答
  • 0 关注
  • 185 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信