How to Redirect HTTP to HTTPS in .htaccess?

The SSL certificate is a digital certificate necessary to validate your website’s identity and authenticity. SSL is a security protocol having the power to create and establish an encrypted connection between a web server and a web browser.

As a standard practice, SSL must be installed on your website to safeguard and secure any sensitive data exchanged between the two systems. With SSL installed, you can keep cyber criminals at bay and prevent them from reading and modifying the transferred data.

Important Notes:

Before editing the code in the .htaccess file, here are a few important points to remember.

You must store your .htaccess file in the Root Folder OR in the same folder where your website is present.
In the .htaccess file, search for the phrase ‘RewriteEngine On.’ If it already exists, add the following relevant code(s) right after it. Do not repeat RewriteEngine ON.
You must type your domain name instead of the example – mydomain.com.

.htaccess Code for migrating HTTP to HTTPS.

Variation 1 – without WWW
Code for a non-www type of website:

Start below “RewriteEngine On”
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ HTTPS://mydomain.com%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Variation 2 – with WWW
Code for a www type of website:

Start below “RewriteEngine On”
RewriteCond %{HTTP_HOST} !^www.mydomain.com [NC]
RewriteRule ^ HTTPS://www.mydomain.com %{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP:X-Forwarded-Proto} !HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ HTTPS://mydomain.com %{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Variation 3 – Redirecting all your web traffic
Code for all web traffic redirection:

Start below “RewriteEngine On”
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ HTTPS://www.yoursite.com/$1 [R,L]

Variation 4 – Redirecting a selected Domain
Code for specific Domain (from multiple domains) redirection:

Start below “RewriteEngine On”
RewriteCond %{HTTP_HOST} ^mydomain\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ HTTPS://www.mydomain.com/$1 [R,L]

Variation 5 – Redirecting a selected Folder or a Webpage
Code for a specific Folder redirection:

Start below “RewriteEngine On”
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ HTTPS://www.mydomain.com/folder/$1 [R,L]

Posted in BlogsTagged ,