【问题标题】:How can I account for a (missing) trailing slash when redirecting root directory to a subdirectory?将根目录重定向到子目录时,如何解决(丢失的)斜杠?
【发布时间】:2018-12-25 22:30:36
【问题描述】:

在我的共享 Apache 主机上,我正在尝试将对我网站的所有请求无缝重定向(无需重写客户端浏览器中的 URL)到名为 /blog 的子目录。我正在使用.htaccess 文件执行此操作。

这是我目前所拥有的(来自here):

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{HTTP_HOST} ^example\.
RewriteRule ^(.*)$ /blog/$1 [L]

这适用于带有斜杠的 URL。

例如当用户访问https://example.com/about/时,来自http://example.com/blog/about/的文件被提供,URL仍然是https://example.com/about/

问题

当用户访问https://example.com/about(没有尾部斜杠)时,来自https://example.com/blog/about/的文件被提供,但浏览器中的URL变为https://example.com/blog/about/。不需要更改 URL。

问题

如何更改我的.htaccess 文件以确保在缺少尾部斜杠时客户端浏览器中的 URL 不会更改?

其他信息

我在提供商后端检查的唯一选项是“强制 SSL”。服务器上没有其他 .htaccess 文件。

【问题讨论】:

    标签: apache .htaccess url-rewriting apache2


    【解决方案1】:

    Apache 的mod_dir 模块正在添加尾部斜杠,因为/blog/about/ 是一个真实目录,并且在目录前面添加了尾部斜杠以防止目录列出。

    您可以使用以下规则:

    DirectorySlash Off
    Options -Indexes
    RewriteEngine On
    
    # add a trailing slash if desrtination is a directory
    RewriteCond %{DOCUMENT_ROOT}/blog%{REQUEST_URI} -d
    RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
    
    RewriteCond %{HTTP_HOST} ^example\. [NC]
    RewriteRule !^blog/ blog%{REQUEST_URI} [NC,L]
    

    请务必在新浏览器中对此进行测试以避免旧缓存。

    【讨论】:

    • 感谢您的回复,但使用您的代码问题仍然存在(使用新浏览器测试)。当我输入 https://example.com/about 时,它仍然会将 URL 重写为 https://example.com/blog/about/
    • 这些规则在我的 Apache 上运行,所以我怀疑你的其他一些冲突规则。您能否在问题中显示完整的 .htaccess 并告诉您的 .htaccess 位于何处?
    • 我也担心会发生一些共享主机魔法。我发布的是完整的 .htaccess 文件。它位于我的网站空间的根文件夹中。
    • 感谢您一直以来的建议,但我将减少损失并收工(我已经尝试了 2 天)。我会接受这个答案,因为它适用于你的盒子 - 我很确定我的终端存在一些共享托管怪异。
    • 今后也可以随时提出与此问题相关的问题,祝您好运。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2019-07-20
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多