Rewrite of Insecure to Secure Domain with Wildcard

apache-2.4httpd.conf

I'm looking for the proper way to handle redirecting of insecure (via port 80) requests to secure (port 443) with Apache server config. I do not want to put this in my .htaccess file either.

Currently I have this in my httpd.conf file:

ServerName example.com
ServerAlias *.example.com

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$
RewriteRule ^(.*)$ https://%1.example.com/$1 [R=302,L]

The goal is to do a wildcard (in subdomain and subfolder) redirect. To be specific, here are some major use cases:

 - http://subdomain.example.com to https://subdomain.example.com
 - http://example.com to https://www.example.com
 - http://www.example.com/contact/ to https://www.example.com/contact
 - http://subdomain.example.com/contact/ to https://subdomain.example.com/contact

In short, simply replacing http with https as long as two conditions meet:

  • The requested URI contains mydomain.com

  • The requested URI is not already secure (http traffic only)

I've tried numerous different methods but nothing seems to capture all variations of subdomains and subfolders, much to my surprise.

Any ideas? Thanks!

Best Answer

A simple virtual host is the best way to catch all the HTTP requests. Then you cannot accidentally redirect HTTPS requests. Something like.

<VirtualHost *:80>
   ServerName example.com
   ServerAlias *.example.com

   # Redirect subdomains.
   RewriteEngine on
   RewriteCond %{HTTP_HOST} (\w+.example.com)
   RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]

   # Everything else to www.example.com preserving URI path
   Redirect 301 / https://www.example.com/
</VirtualHost
Related Topic