.htacces Redirect to HTTPS with WWW


htaccess redirect https www

When you enable SSL/TLS for your website, you will need to redirect your HTTP requests to HTTPS. Since Google treats the www and non-www versions of your site as separate entities, you will also need to redirect non-www pages to www version or vice versa. But what if you want to accomplish both together? Let us look how to .htaccess redirect to HTTPS with www, and how to .htaccess redirect to HTTPS with non-www in Apache

 

Before we proceed please ensure that .htaccess (mod_rewrite) is enabled on your Apache server

 

.htacces Redirect to HTTPS with WWW

The following code will redirect all your HTTP requests to HTTPS and www version of your website. Paste the following code in your .htaccess file and restart Apache.


<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} off [OR]
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
  RewriteRule (.*) https://www.%1/$1 [R=301,L]
</IfModule>

The above code does 3 things:

    1. Checks if mod_rewrite is installed
    2. Checks if HTTPS is off or www is absent in the URL.
    3. If condition #2 is true, then it will redirect the HTTP request to its HTTPS and www version.

 

You can place this code in the .htaccess file created at the root location (/var/www/html). In that case, it will be applicable to all requests to your website.

 

.htaccess redirect to https and non-www

If you want to redirect all HTTP requests to HTTPS and non-www version, then paste the following code in your .htaccess file


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

The above code does 3 things:

  1. Check if mod_rewrite is enabled
  2. Check if URL has HTTPS turned off, or has www
  3. If condition #2 is satisfied, then redirect it to HTTPS and non-www version.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!