如何使用.htaccess减少重定向链?

时间:2018-07-07 18:42:51

标签: .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

2 个答案:

答案 0 :(得分:0)

我用这个

<IfModule mod_rewrite.c>
    RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
        RewriteCond %{HTTPS_HOST} !^www\. [NC]      
         RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [L,R=301]
</IfModule>

答案 1 :(得分:0)

如果我对您的理解正确,那么您想强制使用HTTPS //非WWW并从一个重定向中删除文件中的尾部斜杠。这有点苛刻,并且需要.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年发布了一条推文,“ 30倍重定向不会再失去PageRank。”因此,即使对于SEO,这也不再是一个紧迫的问题。