To avoid this on subdomains, you just a condition which matches only the main domain and not www.
This version will match very generically, any domain which has two parts and doesn't begin with www, not matching any domain with 3 parts where the first isn't www.
RewriteEngine On
# Doesn't start with www
RewriteCond %{HTTP_HOST} !^www\. [NC]
# And does not also have a subdomain
RewriteCond %{HTTP_HOST} !^[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
But this is simpler if you have a fixed set of domains to deal with. Instead of checking for starting with www
, do the redirect only when it matches the bare domain. Add as many domain names into the ( | )
OR grouping as needed.
RewriteEngine On
# Matching any of 3 domains without www, and no subdomain
RewriteCond %{HTTP_HOST} ^(domain1|domain2|domain3)\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]