I have the following which redirects mydomain1.co.uk and mydomain1.com to www.mydomain1.com perfectly.

RewriteCond %{HTTP_HOST} !^(.*)\.mydomain1\.com$ [NC]
RewriteRule ^(.*)$ http://www.mydomain1.com/$1 [R=301,L]

I am trying to add an additional rule for a second domain, that will redirect all non www traffic for mydomain2.com to www.mydomain2.com.



You seems to have quite a few domains and subdomains pointing to the same folder (so they share the same .htaccess) which makes your original approach not suitable for such situation. Use these rules instead of yours:

RewriteCond %{HTTP_HOST} =mydomain1.co.uk [OR]
RewriteCond %{HTTP_HOST} =mydomain1.com
RewriteRule ^(.*)$ http://www.mydomain1.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} =mydomain2.com
RewriteRule ^(.*)$ http://www.mydomain2.com/$1 [R=301,L]

These rules will only work with domains/subdomains described in your question and will not catch any other subdomains (e.g. hello.mydomain1.com will not trigger these rules).

| improve this answer | |

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.