【问题标题】:.htaccess removing file extension is conflicting with folders of the same name.htaccess 删除文件扩展名与同名文件夹冲突
【发布时间】:2021-07-04 20:40:43
【问题描述】:

我正在使用 .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]

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    这是由于与 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}/$1.html -f
    RewriteRule (.*) $1.html [L]
    

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

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

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

    【讨论】:

    • 哇,效果很好,谢谢!只是一个简单的问题,为什么我必须禁用目录列表?我读到它们可能是安全威胁,是不是因为这个?
    • 是的,当您禁用 DirectorySlash 并启用 mod_autoindex (即生成目录列表)时,当您请求不带斜线的目录时,mod_autoindex 将生成目录列表,即使可能有该目录中的 DirectoryIndex 文档通常会阻止生成目录列表。
    • 我还更新了您现有的规则,因为存在一些“漏洞”。我已经用更多解释更新了我的答案。
    猜你喜欢
    • 2015-09-14
    • 2012-12-30
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多