简体   繁体   English

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

[英]How to redirect HTTPS non-www to HTTPS www using .htaccess?

When I visit my site at https://example.com , my browser responds with ERR_CONNECTION_REFUSED.当我在https://example.com访问我的网站时,我的浏览器响应 ERR_CONNECTION_REFUSED。 Note that the following all work:请注意,以下所有工作:

How can I redirect https://example.com requests to https://www.example.com using .htaccess?如何使用 .htaccess 将https://example.com请求重定向到https://www.example.com

I've tried the following which doesn't seem to work:我尝试了以下似乎不起作用的方法:

// .htaccess

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

Your rules is using AND operation between 2 conditions but you OR .您的规则是在 2 个条件之间使用AND运算,但您OR

You can use this rule for enforcing both www and https :您可以使用此规则来强制执行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]

Make sure to clear your browser cache before testing.确保在测试前清除浏览器缓存。


EDIT: As per comments below just for https://example.com to https://www.example.com redirect you can use this rule:编辑:根据下面仅针对https://example.com to https://www.example.com重定向的评论,您可以使用此规则:

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

The rule you have should work as it is.您拥有的规则应该按原样工作。

From ERR_CONNECTION_REFUSED , I would guess Apache isn't listening on the https (443) port.ERR_CONNECTION_REFUSED ,我猜 Apache 没有监听 https (443) 端口。

But since everything else works, even the redirect from http://example.com to https://www.example.com , there might be some other network related problem, like a firewall configuration allowing https through www.example.com, but blocking via example.com.但是由于其他一切正常,即使是从http://example.com重定向到https://www.example.com ,也可能存在其他一些与网络相关的问题,例如防火墙配置允许 https 通过 www.example.com,但通过example.com阻止。 You should check with your server provider.您应该咨询您的服务器提供商。

non-www to www with https非 www 到 www 与 https

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM