Forcing HTTPS and www on root domain, but not on subdomains

I want to force HTTPS throughout the site, which is already done no problem with the below:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]

But I also want to make sure requests that go to the apex domain get redirected to www.example.com

I found this answer, but seems this would redirect subdomains to www as well? ...or maybe it won't as don't subdomains use their own .htaccess?

In addition to the above, I tried the below for the www. portion, but it doesn't seem to work?

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)|webp$ [NC]
RewriteRule ^ https://www.example.com/%{REQUEST_URI} [R=301,L,NC,NE]

I thought this would fail if it doesn't start with example.com and hence will leave ANY subdomain alone, including www?

But it doesn't seem to be triggering at all.


Solution 1:

This config should work for your needs:

RewriteEngine On

# When on the root domain (with HTTPs; on "www" or the root domain only):
#  Redirect to WWW Root
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^(?!www\.)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

# When HTTP is off (on "www" or the root domain only)
#  Redirect to the HTTPs Version of the WWW root
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.|)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

You can also test your config using this website.