19.3 C
Amsterdam
angeloma
Senior Writer and partner

Redirecting all traffic from HTTP to HTTPS with Apache

Hello friends, in this very short post, I will show you how to redirect all the traffic from HTTP to HTTPS with Apache on our web server. This has to work on any Apache-compatible Linux distribution in even FreeBSD.

On a web server, it is always convenient to have access via HTTPS to ensure that all communication is secure. Except for a very few cases on private servers without internet access is that you can afford not to have HTTPS.

So, if a user explicitly writes http:// what we will do is redirect him to https:// with this we will avoid security leaks. There are two methods to do this and in this post, we will explain both.

Redirecting all traffic from HTTP to HTTPS with the VirtualHost configuration

On this site, we use many VirtualHost which is a way to have several sites on one server. Each one of them has a configuration file that we have to create ourselves.

- Advertisement -

In distributions like Debian, Ubuntu, and derivatives, the VirtualHosts configuration files are located in /etc/apache2/sites-available

For CentOS, Red Hat and Fedora in /etc/httpd/conf.d

In summary, what we have to do is add the following clause within the VirtualHost configuration.

Redirect permanent / https://example.osradar.test/

For example, a complete configuration file of a VirtualHost can look like this:

<VirtualHost *:80>
   ServerAdmin admin@your_domain.com
   DocumentRoot /var/www/html/example
   ServerName example.osradar.test
      
    <Directory /var/www/html/example>
         Options FollowSymlinks
         AllowOverride All
         Require all granted
    </ Directory>
Redirect permanent / https://example.osradar.test/
</VirtualHost>

Then save the changes and close the text editor.

To apply the changes, simply restart Apache.

sudo systemctl restart apache2

or in distributions such as Red Hat, CentOS or Fedora:

sudo systemctl restart httpd

This should be enough.

Another way to do it

If you do not have access to the VirtualHost configuration files or if you do not want to modify them, you can do so through the .htaccess file but in this case, it will affect all sites and applications on the server.

To do this, you must open it and add the following lines:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ [your-server-name] [L,R=301]

Save the changes and you’re all set.

Conclusion

Redirecting all traffic to HTTPS may be thought to be difficult but here we have shown you that it is not. Definitely a web server that has an outlet to the Internet has to always try to handle these connections.

So, share this post and join our Telegram Channel.

- Advertisement -

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Donate to Osradar

Latest article