Force HTTPS on a website using .htaccess

how-to-force-https-ssl-on-a-website-using-htaccess

In this article, we will go through on how to force HTTPS on a website using .htaccess.

This article consists on 2 parts:

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

The 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 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) gets broken. So, you have to fix URLs both in the application (if they are hardcoded in the database or config file).

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 .htaccess file of website. The .htacess is located in the public or home directory. If your website is already using .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.

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 above code with your actual site domain.

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

Related Posts