.htaccess - 如何使用 .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
解决方案
如果我理解正确,您想强制 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,这也不再是一个紧迫的问题。
推荐阅读
- haskell - Stack 只找到较新版本的 Cabal
- javascript - 传递参数是 if/else 决策的最佳解决方案
- orange - 橙色测试和分数挂在 0% 几个小时
- google-analytics - 如何将谷歌分析添加到 vaadin 应用程序?
- angular - 模板不使用异步管道呈现 observable
- javascript - 如何使用 d3.js 拖动和旋转正交地图(地球)
- php - 使用dropzone时如何显示回声
- c# - 如何为新的用户实例添加默认角色;
- php - PHP / SQLITE3 问题
- java - 如何在 RecyclerView 的 ViewHolder 中正确实例化 mContentView,避免空对象引用?