henrywright
henrywright

Reputation: 10240

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. Note that the following all work:

How can I redirect https://example.com requests to https://www.example.com using .htaccess?

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] 

Upvotes: 5

Views: 12044

Answers (3)

General Omosco
General Omosco

Reputation: 848

non-www to www with https

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

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74008

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.

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. You should check with your server provider.

Upvotes: 1

anubhava
anubhava

Reputation: 784868

Your rules is using AND operation between 2 conditions but you OR.

You can use this rule for enforcing both www and https:

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:

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

Upvotes: 5

Related Questions