henrywright henrywright - 9 months ago 43
Apache Configuration Question

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]


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]