Rewrite HTTP Requests to HTTPS

Posted by Morgan Billingsley on December 30, 2019 7:39 pm

It’s important to prohibit all insecure connections to your server so that all user activity is secure.

Step 1: Make sure the rewrite module is enabled

If you’re not sure whether or not the rewrite module is enabled, type the following command in your terminal:

sudo apache2ctl -M | grep rewrite

If the above command returns rewrite_module (shared), then the rewrite module is already enabled. If the above command does not return rewrite_module (shared), then you need to visit my post on enabling the apache rewrite module.

Step 2: Adjust the virtual host on port 80

Edit your existing apache virtual host configuration file on port 80. If you do not have an existing apache virtual host configuration file on port 80, pay attention to the final result of this tutorial.

sudo nano /etc/apache2/sites-available/example.com.conf

Add the following settings to your virtual host configuration:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

The final result of your virtual host configuration for port 80 should look similar to this:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/example/public
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
    ErrorLog ${APACHE_LOG_DIR}/example-error.log
    CustomLog ${APACHE_LOG_DIR}/example-access.log combined
</VirtualHost>