Redirect HTTP to HTTPS on Apache Virtual Host


HTTP (Hyper Text Transfer Protocol) is a popular as well as the fundamental protocol for data communication on the World Wide Web (WWW); typically between a web browser and the server which stores web files. Whereas HTTPS is the secure version of HTTP, where the ‘S‘ at the end stands for ‘Secure‘.

Using HTTPS, all data between your browser and the web server are encrypted thus secure. This tutorial will show you how to redirect HTTP to HTTPS on Apache HTTP server in Linux.

Before you can set up an Apache HTTP to HTTPS redirect for your domain, make sure you have SSL certificate installed and mod_rewrite is enabled in Apache. For more information on how to setup SSL on Apache, see following guides.



Step 1- Redirect HTTP to HTTPS on Apache Virtual Host
To force all web traffic to HTTPS, We can add a single line of code in Apache Virtual host configuration section. modify your Virtual host that is configured for non-secure access using port 80.
$ sudo vi /etc/apache2/sites-available/000-default.conf
Add the following line between your Virtual host configuration and Your Virtual host configuration file should be like this.
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        redirect / https://192.168.102.10
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
Save and exit from the file.
Restart Apache service to apply changes.
$ sudo systemctl restart apache2.service
Check your website- In my case, I am using the server IP address - http://192.168.102.10

Your website has been successfully redirected to https domain.
!!cheers!!

No comments:

Post a Comment