I think the following would do the trick:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} ^on
RewriteCond %{HTTP_HOST} (?:([^.]+)\.)?mywebapp\..*
RewriteRule ^.* https://%1mywebapp.com%{REQUEST_URI} [R=302,L] #removed double slash
RewriteCond %{HTTP_HOST} !.*\.com
RewriteCond %{HTTPS} !^on
RewriteCond %{HTTP_HOST} (?:([^.]+)\.)?mywebapp\..*
RewriteRule ^.* http://%1mywebapp.com%{REQUEST_URI} [R=302,L] #removed double slash
Here's what it's saying:
- Create a
RewriteRule
only if%{HTTP_HOST}
does not contain .com - check protocol and only continue if is https
- Run a regex to check if subdomain exists and store subdomain if it does (referenced by
$1
) - Manually force the
.com
, preceed it with subdomain, concatenate the%{REQUEST_URI}
and then redirect (I left it as a302 Temporary Redirect
so you can play with it as needed. I would go to a301
until you are 100% ready)
Edit: I duplicated the rule set to handle the protocol issue. So apparently you can only get the last backreference. Meaning that when the protocol was https, it would overwrite the subdomain stored in %1
backreference. By having a ruleset for either protocol, you circumvent the issue. Likely not the prettiest way, but it should get the job done.