.htaccess:在没有 www 的情况下重定向到 https 导致循环

.htaccess: redirect to https without www results in loop

我正在尝试将我的 URL 重定向到 https。我想执行以下操作:

http://example.com => https://example.com 
http://www.example.com => https://example.com 
www.example.com => https://example.com 
example.com => https://example.com 

所以将每个 URL 转换为 https://example.com(删除 www)!

我当前的 .htaccess 如下所示:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^example.com [NC] 
RewriteRule ^(.*)$ https://example.com / [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png|\.ogg|\.wav|\.mp3|\.mp4|\.zip|\.pdf|\.fav|\.rar|\.doc)$ [NC]
RewriteRule ^(.*)$ /index.php?q= [L,QSA]

我尝试添加

RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

在第一个 RewriteRule 之后和之前,但它会导致无限循环。 有人可以帮助我吗?

将您的第一条规则更改为:

# remove www and turn on https in same rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

并在测试前清除浏览器缓存。

我在这里找到了我的解决方案:

https://serverfault.com/questions/677560/redirect-loop-when-forcing-https/678402#678402?newreg=f6df6f796eb343a5bbbe1da54c51f93b

### Force HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]