Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • https://www.example.com
  • http://example.com redirects to https://www.example.com
  • http://www.example.com redirects to https://www.example.com

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] 
like image 661
henrywright Avatar asked Aug 19 '16 14:08

henrywright


1 Answers

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]
like image 113
anubhava Avatar answered Sep 24 '22 05:09

anubhava