# Redirect for subdomains and secondary domains

I've just edited my .htaccess file. All works as it should, but I'm not too familiar with regular expressions and want to make sure that there aren't any unintended consequences.

I want to:

1. Add www to the domain if it's not there (i.e. domain.com becomes www.domain.com)
2. redirect from secondary.primary.com to www.secondary.com (the site is a subdomain of another site but the two aren't related and the primary domain shouldn't be included in the URL for the site).
3. redirect domain.com/staging to staging.domain.com.

Here are my rules:

# Add www if not there
RewriteCond %{HTTP_HOST} ^secondary\.com$[NC] RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]

# Prevent search engine from using secondary domain i.e. secondary.primary.com and instead use secondary.com
RewriteCond %{HTTP_HOST} ^(www\.)?secondary\.primary\.com$[NC] RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]

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


# Prevent access to staging through secondary.com/staging and instead use staging.secondary.com
RewriteCond %{HTTP_HOST} ^secondary.com [NC]
RewriteRule ^(.*)$http://www.secondary.com$1 [L,R=301]


… is basically a sloppier version of your first rule with a misleading comment.

The remaining two mod_rewrite rules can be combined as:

# Canonicalize hostname of secondary domain
RewriteCond %{HTTP_HOST} ^$secondary\.com$|^(www\.)?secondary\.primary\.com$[NC] RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]


Note that if your site supports HTTPS, the rule would redirect HTTPS requests to unencrypted HTTP.

• How would I prevent redirecting HTTPS to HTTP? – amylynn83 Jul 8 '15 at 13:32