How to redirect HTTP non-www to HTTPS www through .htaccess

By | 06 th Sep 2021 | 1 min read

HTTPS combines HTTP with the Secure Socket Layer (SSL) / and Transport Layer Security (TLS). SSL works by using a public key to encrypt data transferred over the connection, allowing us to communicate securely with the webserver. Suppose we have an SSL certificate installed for the website. In that case, we need to make sure that the HTTP URLs are redirected to the HTTPS URLs to ensure that all the connections from the website are accessed through the secure encrypted channel. 

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC]

RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

# We are not using www as non www was already redirected to www.

RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

The rule mentioned above allows you to redirect the HTTP non-www URL to HTTPS www URL.