如何使用.htaccess将子目录重定向到根目录并同时删除HTML扩展名?

3
我尝试将子目录重定向到根目录并去掉 .html ,但我的操作发生了问题。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# RedirectMatch 301 ^/path/$ http://testdomain.com/
# RedirectMatch permanent ^/path/$ http://testdomain.com/
# RedirectMatch 301 ^/path/.*$ http://testdomain.com/
# RewriteRule ^path/(.*)$ /$1 [R=301,NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]

</IfModule>

我删除链接扩展名中的.html没有遇到任何问题并成功获得了结果

但是,我无法获取根目录下的子目录链接。我尝试每次清除前四行的#,但是没有得到结果。

我需要像这样完成此操作:

http://testdomain.com/path/hello.html
to
http://testdomain.com/hello

现在我用这段代码,可以去除HTML扩展名,我的链接状态如下:
http://testdomain.com/path/hello.html
TO
http://testdomain.com/path/hello

现在我需要清空我的“路径”文件夹。

同时,我遇到了404 Not Found错误,请指导我。

1个回答

1
您可以用这个规则替换您的规则:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/path/$1.html -f
RewriteRule ^(.+?)/?$ path/$1.html [L]

1
您好,这里有一个问题,您是如何得出规则中 %{DOCUMENT_ROOT}/path/$1.html -f 条件的线索的呢?如果这是个愚蠢的问题,请见谅 :) 谢谢。 - RavinderSingh13
1
这是因为 OP 想要检查 DocumentRoot 文件夹下的 path/ 子目录中是否存在 HTML 文件。 - anubhava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接