21

我试图强制用户被重定向到非 www 网站,并强制 https。

当输入 http 时,我已经完成了这项工作,但不强制使用 https。

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://site.com\.net/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

关于我做错了什么的任何想法?

4

4 回答 4

48

试试这个规则:

RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]
于 2011-06-14T16:59:18.563 回答
5

根据 Gumbo 的评论:“TLS/SSL 连接已建立,证书在传递给 HTTP 并发生 HTTP 重定向之前已得到验证”我试了一下(这似乎可行):

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.blahblah.com/$1 [R,L]

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

请告诉我这种方法是否有问题。

于 2014-09-11T23:23:53.820 回答
3

唯一对我有用的规则如下

# match any URL with www and rewrite it to https without the www
    RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
    RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]

# match non https and redirect to https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

顺序很重要,它在某些情况下会阻止第三次重定向。

于 2016-10-12T01:44:37.020 回答
0

使用此代码,我从 http 和 www 和无 www 重定向到 https 无 www。请注意在 htaccess 中插入代码的位置很重要:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
于 2021-11-12T06:02:07.410 回答