QuickTip: Redirect from HTTP to HTTPS on Apache Server

SSL encryption is always the best idea to protect sensitive data against third parties. But what does if the SSL certificate is installed on the root server/managed server and the encryption is activated, but the website is still accessible via HTTP? An unsecured protocol for secure transfer of data from the server to the browser.

Therefore the HTTP  protocol should be forwarded to HTTPS protocol. Depending on which areas/ folders of the website you want to protect with encryption,  You can expand the configuration so that it only accesses certain directories or requests.

You can fork the configuration so that the visitors only accesses certain directories or requests with secure and non-secure connections.

HTTP to HTTPS via htaccess

The .htaccess file should be located directly in the root directory of the web page. In my example, all web page calls, which are sent to the server via HTTP, are converted to HTTPS. For the user, this process is actually completely unnoticed, since the process takes place in the background.

In my example, all requests, which are sent to the server via HTTP, are redirected to HTTPS. For the user, this process is actually completely unnoticed, since the process takes place in the background.

For the visitor, this process is actually completely unnoticed, since the process takes place in the background at the server end with no visible trace to the visitor.

<ifmodule mod_rewrite.c="">
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</ifmodule>

Explanation of Above Code:

Line 1: Checks whether the module mod_rewrite is activated
Line 2: Activates the Rewrite Engine
Line 3: Checks if HTTPS is switched on, if not, it executes the contents of line 4 from
line 4: directs all requests via status code 301 (permanent redirect) HTTPS

HTTP to HTTPS via the Apache Vhost configuration

This method will apply to the complete domain, unlike in the previous method.

So open the virtual host configrutaion of the site with your favorite editor like nano.

And paste the following code.

<virtualhost domain.com="">
ServerName domain.com
DocumentRoot /var/www/website1
    <ifmodule mod_rewrite.c="">
      RewriteEngine On
      RewriteCond %{HTTPS} off
      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </ifmodule>
</virtualhost>
Now all the calls to the site http://domain.com are redirected to https://domain.com.
And make sure the domain is configured properly with SSL before redirection if not there will be a problem.