.htaccess 删除文件扩展名与同名文件夹冲突

.htaccess removing file extension is conflicting with folders of the same name

我正在使用 .htaccess 文件从 url 中删除文件扩展名(如 .html)。文件中的代码工作正常,但只要有一个与文件同名但没有扩展名的文件夹,它就会重定向到该文件夹​​而不是重定向到文件。例如,如果我在同一目录中有一个 demo.html 文件和一个 demo 文件夹,只要我在浏览器的搜索栏中键入 www.example.com/demo,它就会重定向到该文件夹​​,而不是的文件。如果我删除该文件夹并再次键入相同的内容,它会完美运行!任何帮助,将不胜感激 :) 这是 .htaccess 文件中的代码:

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

这是由于与 mod_dir 的冲突造成的。当您请求一个没有尾部斜杠的目录时,mod_dir 将“修复”URL 并附加尾部斜杠和 301 重定向。之后它将尝试提供 DirectoryIndex 文档。这优先于您的内部重写。

要解决此问题,您需要使用 DirectorySlash Off 禁用此行为。

例如:

# Ensure that directory listings are disabled
Options -Indexes

# Prevent mod_dir appending a slash to physical directories
DirectorySlash Off

# Redirect to remove the ".html" extension
RewriteCond %{THE_REQUEST} /([^.?]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R=301]

# Rewrite request to append ".html" extension if it exists
RewriteCond %{DOCUMENT_ROOT}/.html -f
RewriteRule (.*) .html [L]

目录列表 (mod_autoindex) 在禁用 DirectorySlash 时需要禁用,因为如果 mod_autoindex 启用,那么当您请求不带斜杠的目录时,目录列表将是生成,无论您在该目录中是否有 DirectoryIndex 文档(例如 index.html)通常会阻止生成目录列表。

此外,我已经“修复”了您删除和附加 .html 扩展名的现有规则。删除 .html 扩展名的第一条规则可能与查询字符串中出现的 .html 实例匹配。如果请求 /demo/<does-not-exist>,附加 .html 扩展名的第二条规则将导致重写循环(500 错误) - 其中 demo 是目录和文件基名(如您的例如)。

有关此潜在重写循环的更多信息,请参见有关 ServerFault 的相关问题 my answer