How to Redirect HTTP to HTTPS on Apache

By | January 15, 2019

A secured HTTP (Hyper Text Transfer Protocol) is better when working with logins and confidential data. Plain HTTP is insecure, every ISP(s) or any middle man, between the client and server, can read all the data which is being transferred between them. However in HTTPS every communication gets encrypted.

Redirecting all http traffic to https is straight forward in apache. Before redirecting http to https, make sure you have SSL certificate installed. Additionally mod_rewrite should be enabled in Apache.

In Ubuntu/Debian enable mod_rewrite using

sudo a2enmod rewrite

In CentOS/RHEL enable it using

LoadModule rewrite_module modules/mod_rewrite.so

Now, forwarding traffic is easy. We can directly edit the .conf file. Or we can add .htaccess file in the particular directory, and add these lines.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] Now everytime a visitor types ‘http://yourdomain.com’ it automatically redirects to ‘https://yourdomain.com’.