Another way would have been to check for mydomain1
in the hostname and is not www.mydomain1.com
(the canonical hostname) then redirect to the canonical hostname.
For example:
RewriteCond %{HTTP_HOST} mydomain1 [NC]
RewriteCond %{HTTP_HOST} !^www\.mydomain1\.com$
RewriteRule (.*) http://www.mydomain1.com/$1 [R=301,L]
This handles any number of variations of mydomain1
(assuming mydomain1
could not legitimately occur as part of mydomain2
) and FQDN that end in a dot. Then repeat for mydomain2
.
If both domains have the same canonical hostname format (ie. www.example.com
, as in your example) then you could combine these two (or more) rules into one:
RewriteCond %{HTTP_HOST} (mydomain1|mydomain2) [NC]
RewriteCond %1@@%{HTTP_HOST} !^([a-zA-Z]+)@@www\.\1\.com$
RewriteRule (.*) http://www.%1.com/$1 [R=301,L]
The \1
in the second CondPattern is an internal backreference to the domain name matched in the first condition. %1
is a backreference to the last matched CondPattern (ie. the domain name in the first CondPattern). The second condition is never "matched" since it is a negated pattern.