如何使用.htaccess将HTTPS非www重定向到HTTPS www?

问题描述:

当我访问我的网站https://example.com时,我的浏览器响应ERR_CONNECTION_REFUSED。请注意,以下各项工作:如何使用.htaccess将HTTPS非www重定向到HTTPS www?

我如何可以重定向https://example.com请求https://www.example.com使用的.htaccess?

我已经试过这似乎并没有工作如下:

// .htaccess 

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

你的规则是使用2个条件,但你OR之间AND操作。

您可以使用此规则强制执行既wwwhttps

RewriteEngine On 

RewriteCond %{HTTP_HOST} !^www\. [NC,OR] 
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] 
RewriteRule^https://www.%1%{REQUEST_URI} [R=301,L,NE] 

确保在测试前先清除浏览器缓存。


编辑:按下面只是https://example.com to https://www.example.com意见重定向您可以使用此规则:

RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteRule^https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE] 
+0

我试过这个,但我认为它与httpd.conf中的现有规则冲突。只有当请求是“https:// example.com”时,是否有重定向到www的方法? – henrywright

+0

如果原始URL是'http:// www.example.com',那么你不需要成为'https:// www.example.com'。顺便说一句,你可以在httpd.conf中使用这个规则,只记得重新启动Apache并清空浏览器缓存(或使用curl命令行进行测试) – anubhava

+0

感谢您的建议@anubhava。 'http:// www.example.com'已经重定向到'https:// www.example.com'。它只是需要处理的'https:// example.com'到'https:// www.example.com'。 – henrywright

你应该工作,因为它是规则。

ERR_CONNECTION_REFUSED,我猜Apache不会在https(443)端口上侦听。

但是由于其他一切正常,即使从http://example.com重定向到https://www.example.com,也可能存在其他一些与网络有关的问题,例如防火墙配置允许https通过www.example.com,但通过example.com阻止。你应该检查你的服务器提供商。

+0

谢谢,这是有用的知道。我会检查! – henrywright