首页 > 解决方案 > 如何使用 .htaccess 减少重定向链?

问题描述

我在解决我的网站的重定向链时遇到了一些问题。我希望我的网站最终只有一个版本,即HTTPS + 非 www + 斜杠

测试时,在 htaccess 下面给了我 4 个响应,其中重定向链在 8 个测试的总变体中(https、www/non-www、斜杠、2x2x2 = 8 变体)。

http:// www 。变体给了我一个带有 3 个重定向 http://www的重定向链。--> https://www。--> https://www。+ 斜杠 ---> https:// + 斜杠

有没有办法让它没有重定向链或至少不超过2个?

感谢有人可以帮助我!谢谢

# Force trailing slash
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1/ [L,R=301]

# HTTPS forced by SG-Optimizer
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>
# END HTTPS

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

标签: .htaccess

解决方案


如果我理解正确,您想强制 HTTPS//non-WWW 并在一个 redirect中从文件中删除尾部斜杠。这有点要求,并且需要在 .htaccess 文件中使用某种 GOTO/SKIP 逻辑。在隐身模式下使用新的浏览器尝试这样的操作:

RewriteEngine on

## Check if not a directory and ends in /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
## If not a directory skip next RewriteRule
RewriteRule ^ - [S=2]

## Check if HTTPS and non-WWW
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC]
RewriteCond %{https} off

## This RewriteRule skipped if URI was a directory
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

## This RewriteRule used if URI was a directory
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [S=1]
RewriteRule ^(.*)/$ https://example.com/$1 [R=301,L]

PS:我明白了,但 Google 的 Gary Illyes 在 2016 年发推文说“30x 重定向不再失去 PageRank。” 因此,即使对于 SEO,这也不再是一个紧迫的问题。


推荐阅读