Enforce https and www in a single htaccess rule

Enforce https and www in a single htaccess rule

It is quite possible to redirect http and non www requests to https and www with one single redirect using a RewriteRule in htaccess.
Assuming, you want your site visitors to always redirect to https://www version of your site regardless of they come by http or non-www you can use a single redirect Rule that can both non-https and non-www. The benifit using a single redirect is that your site URLs will load faster as the one single rule is triggered when your visitors visit the http or non www version of your site.

writing a single redirect rule

You need to use a combination of RewriteCond directives and an OR flag between them so that the rule can run if one of the conditions is true.
In the following example we will use two conditions to match against HOST and HTTPS header we use [OR] flag to make the rule run when either HTTP_HOST or HTTPS condition is matched.

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTPS} off

Explanations :
The first condition matches against the host header ie example.com. Replace it with your non-www domain name.
The second condition matches against HTTPS variable . The off represents http non-ssl. This condition is met when the URL scheme is http.
You can use RewriteRule directive just bellow the condition to redirect your non-ssl and non-www urls to https://www.

RewriteRule (.*) https://www.example.com/$1 [L,R]

The following is the complete htaccess rule to enforce ssl and www in a single redirect

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

http to https www generic rule

If you have more then one domain to redirect, then instead of using multiple above codes , you can just use one dynamic rule :

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *