Redirect HTTP Requests To HTTPS On Apache 2
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 OnRewriteCond %{HTTPS} !=onRewriteRule ^/?(.*) 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>
Written by Lami Adabonyan
Want to contribute?
You could earn up to $300 by adding new articles
Submit your article
Suggest an update
Request an article
Suggest an update
Request an article
Leave a Comment