force https in apache

How to Force HTTPS in .htaccess in Apache

HTTPS protocol protects websites from malicious attackers and improves website security. However, once you have installed SSL certificate and enabled HTTPS on your website, it is important to redirect all HTTP URLs on your website to their HTTPS versions. Otherwise, your website URLs will continue to be accessible via both HTTP and HTTPS protocols. In other words, you need to enforce HTTPS on your website. In this article, we will look at how to force HTTPS in Apache.


How to Force HTTPS in .htaccess in Apache

Here are the steps to force HTTPS in .htaccess in Apache. We will basically redirect HTTP URLs to HTTPS as per our requirement using .htaccess in Apache.


1. Open .htaccess file

Open terminal and run the following command to open .htaccess file in your website’s root folder. If your website root is located somewhere else, then please update the file path below as per your requirement.

$ sudo vi /var/www/html/.htaccess


2. Force HTTPS

Add the following lines to enforce HTTPS for all URLs on your website. The following lines basically redirect all HTTPS URLs to their HTTPS version.

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

In the above code, Apache basically checks if the requested URL has HTTPS protocol. If not, then it redirects that URL to its HTTPS version.

If you want to force HTTPS for only URLs in a specific folder e.g. /downloads then create/open .htaccess file in that subfolder and add the above lines in it.

$ sudo vi /var/www/html/downloads/.htaccess

In this case, only the HTTP URLs starting with /downloads will be redirected to their HTTPS versions.


3. Restart Apache Server

Restart Apache server to apply changes.

$ sudo service apache2 restart


In this article, we have learnt how to enforce HTTPS in Apache server, for all URLs on your website. We have also learnt how to force SSL for specific URLs in a folder or subfolder on your site, instead of applying it site-wide.

It is always a good practice to redirect all HTTP URLs to their HTTPS versions to protect your website. Otherwise, your URLs will be accessible via HTTP as well as HTTPS links. Attackers may listen to the HTTP data transmitted over the network, and exploit any vulnerabilities on your website. So make sure that your website URLs are accessible only via HTTPS and if someone requests an HTTP URL, they are automatically redirected to its HTTPS version.

Also read:

How to Set Content-Disposition Header in Apache
How to Get Package Details in Ubuntu
How to Force Download in Apache
How to Copy to Clipboard in Javascript
How to Check Commands Executed by Users in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *