Redirect All HTTP URLs to HTTPS while Preserving Path on Apache with mod_rewrite


To ensure all requests to a web site or service otherwise provided over unencrypted HTTP end up shoved onto HTTPS (TLS, formerly known as SSL), whether they come from errant resource calls on a webpage or the casual user simply entering the hostname in their browser's address bar without specifying the protocol and lacking an always-use-https browser plugin (you know, normal folk), you can use the following snippet in your httpd.conf, VirtualHost blocks or .htaccess files in DocumentRoots (or anywhere below, for finer-grained specificity) and it will make sure they end up getting to where they originally intended to go - though properly encrypted and protected from MiTM (Man-in-the-Middle) attacks etc. - in a Search Engine Optimised (SEO) and user-friendly fashion.

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

Now you may wish to head on over to Let's Encrypt to get yourself a nice, free 90 day SSL certificate for your hostname or, if you prefer, a wildcard cert to plaster on everything that ends in your domain. Try to get certbot (the vendor provided software) to renew it automagically so you're not driven mental manually renewing your cert(s) every three months.


There are no comments for this item.