I know there are many similar threads, but none of them seems to match my exact problem. Here is what I’m trying to do:
(1) http://www.mydomain.com/ -> ht
Non of the examples worked for me, they just seemed to get stuck in a loop, the following works though.
# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]
# match non https and redirect to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
The order matters, it will prevent a 3rd redirect in some cases.
If you want to use a sub domain (anything other than www.) just remove the first ruleset.
So for sub domains all you need is
# match non https and redirect to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
I use Cloudways services and I've found this to be the only thing that works