nginx,

Redirect HTTP to HTTPS in Apache

Dec 28, 2021 · 1 min read · Post a comment
Redirect HTTP to HTTPS in Apache

Securing your website by setting redirect from HTTP to HTTPS in Apache can be achieved easily if your SSL certificate is generated and ready to use. It can be done using a virtual host and .htaccess. I’m going to cover both of them.

Prerequisites

  • Apache
  • Generated SSL Certificate

Mod_Rewrite

First step is to enable the mod_rewrite module.

  • Debian based:
    sudo a2enmod rewrite
    
  • RHEL based:
    Open the httpd.conf file and ensure that you have the following line:
    LoadModule rewrite_module modules/mod_rewrite.so
    

Redirect HTTP to HTTPS using Apache Virtual Host

Using a virtual host is the most common and preferred way of redirecting the traffic from HTTP to HTTPS in Apache.

Open the following virtual host files:

  • RHEL based distro : /etc/httpd/conf.d
  • Debian base distro : /etc/apache2/sites-available

and use the config below:

<VirtualHost *:80> 
  ServerName devcoops.com
  ServerAlias www.devcoops.com

  Redirect permanent / https://devcoops.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName devcoops.com
  ServerAlias www.devcoops.com

  Protocols h2 http/1.1
  # Load the SSL Path Config
</VirtualHost>

Restart the Apache Server.

  • Debian based:
    sudo systemctl reload apache2
    
  • RHEL based:
    sudo systemctl reload httpd
    

Redirect HTTP to HTTPS using .htaccess

Put the following lines in your .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://devcoops.com/$1 [L,R=301]

Conclusion

If you need any other specific rules regarding Apache Virtual Hosts or .htaccess don’t hesitate to put a comment below. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.