Forward HTTP to HTTPS using Apache VirtualHost on an Ubuntu Server

Assuming you are running Apache as your web server, have already secured an SSL certificate, and have both ports 80 and 443 open, you can forward all of your HTTP (http://example.com) traffic to HTTPS (https://example.com) and pass the path along as-is using the following configuration file.

 <VirtualHost *:80>

	ServerAdmin admin@example.com
	ServerName example.com

	RewriteEngine on
	RedirectMatch "^/(.+)" "https://example.com/$1"

 </VirtualHost>

 <IfModule mod_ssl.c>
	<VirtualHost *:443>
  
		ServerAdmin admin@example.com
		ServerName example.com

		RewriteEngine on
		RedirectMatch "^/(.+)" "https://example.com/$1"

		Include /etc/letsencrypt/options-ssl-apache.conf
		SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
		SSLCertificateKeyFile /etc/letsencrypt/live/example/privkey.pem

	</VirtualHost>
 </IfModule>

When running apache2 on an Ubuntu server this file is can be created at /etc/apache2/sites-available/example.com.conf . Once your file is in place you’ll want to run sudo a2ensite example.com  to enable the site and then sudo service apache2 restart to restart your web server and make sure your settings take effect.