猿问

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

我需要能够将目录中的所有 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?


喵喵时光机
浏览 186回答 3
3回答

holdtom

错误与此有关&nbsp;RewriteRuleRewriteRule&nbsp;/sub/directory/index\.php&nbsp;-&nbsp;[L]请参阅匹配什么?在每个目录的上下文(目录和 .htaccess)中,模式只匹配部分路径,例如“&nbsp;/app1/index.html&nbsp;”的请求可能会导致与“&nbsp;app1/index.html&nbsp;”或“index”的比较.html”取决于 RewriteRule 的定义位置。和“每目录重写”:删除的前缀总是以斜杠结尾,这意味着匹配发生在一个从来没有前导斜杠的字符串上。因此,带有 ^/ 的模式永远不会在每个目录的上下文中匹配。这意味着,前导斜杠会阻止模式匹配。将其更改为RewriteRule&nbsp;^sub/directory/index\.php&nbsp;-&nbsp;[L]将解决问题。在500内部服务器错误来自于第二规则(在组合与非匹配的第一规则)。RewriteRule&nbsp;^.*$&nbsp;/sub/directory/index\.php这会将任何请求重写为/sub/directory/index.php,然后将再次重写为/sub/directory/index.php,依此类推,直到重写模块放弃并显示“重定向过多”错误或类似错误。

四季花海

另一种方法,您可以使用此代码:(注释第二行和第三行以接受 url 中的偶数文件和目录)&nbsp; &nbsp; 重写引擎开启&nbsp; &nbsp; RewriteCond %{REQUEST_FILENAME} !-f&nbsp; &nbsp; RewriteCond %{REQUEST_FILENAME} !-d&nbsp; &nbsp; 重写规则 ^(.*)$ /index.php?path=$1 [NC,L,QSA]

眼眸繁星

语法错误,在第二个匹配(不是最后一个)之后另外重新匹配第一个规则。任何请求 -> /sub/directory/index.php -> /sub/directory/index.php - [L]<IfModule mod_rewrite.c>&nbsp; &nbsp; RewriteEngine On&nbsp; &nbsp; # RewriteRule /sub/directory/index\.php - [L]&nbsp; &nbsp; RewriteRule ^(.*)$ /sub/directory/index.php [L]</IfModule>我的另一个建议(index.php 是目录索引文件,在请求目录时是第一个):<IfModule mod_rewrite.c>&nbsp; &nbsp; RewriteEngine On&nbsp; &nbsp; RewriteRule ^sub/directory/(.*)$ /sub/directory/ [R=301,L]</IfModule>
随时随地看视频慕课网APP
我要回答