Redirect HTTP Requests To HTTPS On Apache 2

Updated on November 21, 2023
Redirect HTTP Requests To HTTPS On Apache 2 header image

Introduction

This writeup shows you how to setup Apache 2 to redirect non-secure (http) requests to secure (https) ones.

Pre-requisites

  • You have a Vultr Linux instance running Apache 2.
  • Your have domain name (e.g example.com) whose DNS A records for "@" and "www" are pointing to the IP of your Vultr machine above.
  • Ideally you should also have SSL setup on your instance.

Setup redirect

Make sure Apache's mod_rewrite module is enabled by running sudo a2enmod rewrite.

Method 1:

Put below snippet in a .htaccess file in your site's root folder.

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

Method 2:

Setup the http virtual host (at port 80) to forward to secure virtual host setup instead.

<VirtualHost *:80>
    ServerName example.com
    ServerAlias example.com www.example.com
    Redirect 301 / https://example.com/
</VirtualHost>

<VirtualHost _default_:443>
    ServerName example.com

    SSLEngine On
    #other vhost settings go here (e.g. ssl, logs, site root)
</VirtualHost>