一段时间以来,我一直在使用以下 .htaccess 将非 https 重定向到 https:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
然而,本周一位 SEO 专家告诉我,这为这样的链接提供了 2 个重定向:
www.example.com/test
第一个到http s ://www.example.com/test 第二个到 http s ://www.example.com/test /
显然这对 SEO 不利,所以我尝试在最后一行添加/,这对文件不起作用,例如
www.example.com/test.php => https://www.example.com/test.php/
我进行了一些搜索,但似乎无法找到解决这两个问题的方法。谁能指出我正确的方向?
最佳答案
如何在规则中添加对目录的检查(一个用于目录,一个用于文件):
<IfModule mod_rewrite.c>
RewriteEngine on
# for directories without trailing slashes
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
# for everything else
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
然而,这很有可能无法工作,因为从 /test
到 /test/
的重定向不是通过重写发生的,而是通过 mod_dir 的 >DirectorySlash
指令。如果你真的只想做这个重定向(我认为影响没有那么严重),那么你可以关闭 DirectorySlash
并通过 mod_rewrite 进行重定向相反:
DirectorySlash Off
<IfModule mod_rewrite.c>
RewriteEngine on
# for directories without trailing slashes
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
# for everything else
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Add trailing slashes for directories that have them missing
RewriteCond %{HTTPS} on [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L]
</IfModule>
关于.htaccess 重定向添加尾部斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48912129/