将根目录重定向到子目录时,如何解释(丢失的)尾部斜杠?
How can I account for a (missing) trailing slash when redirecting root directory to a subdirectory?
在我共享的 Apache 主机上,我试图将对我网站的所有请求无缝重定向(无需在客户端浏览器中重写 URL)到名为 /blog
的子目录。我正在使用 .htaccess
文件执行此操作。
这是我目前所拥有的(来自here):
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{HTTP_HOST} ^example\.
RewriteRule ^(.*)$ /blog/ [L]
这适用于带有尾部斜线的 URLs。
例如,当用户访问 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 在缺少尾部斜杠时不发生变化?
附加信息
我在提供商的后端检查过的唯一选项是 "force SSL"。服务器上没有其他 .htaccess
个文件。
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]
确保在新浏览器中测试它以避免旧缓存。
在我共享的 Apache 主机上,我试图将对我网站的所有请求无缝重定向(无需在客户端浏览器中重写 URL)到名为 /blog
的子目录。我正在使用 .htaccess
文件执行此操作。
这是我目前所拥有的(来自here):
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{HTTP_HOST} ^example\.
RewriteRule ^(.*)$ /blog/ [L]
这适用于带有尾部斜线的 URLs。
例如,当用户访问 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 在缺少尾部斜杠时不发生变化?
附加信息
我在提供商的后端检查过的唯一选项是 "force SSL"。服务器上没有其他 .htaccess
个文件。
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]
确保在新浏览器中测试它以避免旧缓存。