Force HTTPS on a website using .htaccess

Force HTTPS on a website using htaccess

When an SSL certificate is installed on a website, it is required to force HTTPS on a website. In this article, we will see how to force HTTPS on a website using .htaccess.

This article consists of 2 parts:

  1. Force HTTPS on a website using .htaccess;
  2. Forcefully add www in your site domain along with HTTPS using .htaccess

HTTPS is the secure protocol for loading HTTP requests. When you have installed the SSL certificate on your website, your site will load both on HTTP and HTTPS. To make sure your site always loads on HTTPS, you have to forcefully redirect the site to HTTPS.

After installing an SSL certificate, your domain will open on HTTPS. But you will notice that the website assets (images, CSS and JS) get broken. So, you have to fix URLs both in the application (if they are hardcoded in the database or config file).

Force HTTPS on a website using .htaccess:

Here is a quick fix for forcing HTTPS on a website using .htaccess:

RewriteEngine On 
RewriteCond %{HTTPS} !=on 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

You have to add the above code in the .htaccess file of the website. The .htacess is located in the public or home directory. If your website is already using the .htaccess file then you can simply add the code. However, it is required to be careful in working with .htaccess as it can easily break your website if incorrect code is added.

Forcefully add www in your site domain along with HTTPS using .htaccess

You can also read about how to force a website to load on www using .htaccess below:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^yoursite\.com [NC] 
RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R=301,L]

Don’t forget to replace the yoursite in the above code with your actual site domain.

Also, see 5 methods to redirect old domain to new domain using .htaccess

Tags:

Related Posts