Last Updated on April 14, 2021 by Amit

Htaccess redirect http to https non www to www
If you are looking for an htaccess RewriteRule that enforces www and https in one redirection and without creating multiple redirects then you have come to the right place. On this article I am going post a 100 percent working rule that you can just copy and paste to your htaccess file.

Here is the RewriteRule :

RewriteEngine on

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

How to use the code : You can just copy and paste it to your htaccess. Since this redirects all non-www and non-https URLs to https://www this is the main rule and should be placed at the top of your htaccess file.
What needs to be changed : You need to change the domain name to your domain. Replace example.com with yourdomain.com in the code and test the rule , if it works then change R to R=301 in the flag section to make the redirection permanent and browser cache-able.

http to https multiple domains

If you are looking for a rule the redirection dynamically, and you don’t want to change hostname manually, then the following one should fullfill your need as it can redirect multiple domains

RewriteEngine on

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

The rule above applies to multiple domains at the same time. You don’t need need to change anything in the rule as it automatically detects host and https headers.

RewriteRule for Cloudflare users

If your domain is on cloudflare then the rules I posted above might fail to work as Cloudflare doesn’t recognise %{HTTPS} variable. Cloudflare has its own variable to test URL scheme. RewriteEngine on RewriteCond %{HTTP:CF-Visitor} ‘”scheme”:”http”‘ is the variable Cloudflare uses to detect URL scheme.
So in that case, you can you can use the following RewriteRule :

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www. [NC,OR]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$
RewriteRule ^(.*)$ https://www.%1/$1 [L,R]

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.