www, non-www and subdomains
If you want to redirect non www users to www version of your website, you can use the following code:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
but in case of sub domains, this’ll create problems. The code above redirects anything *except* www.example.com to www.example.com.
You’d undoubtedly be happier using a positive-match pattern, instead of the negative match used in the above example.
RewriteEngine On
#
# Redirect www.<subdomain>.example.com/<anything> to <subdomain>.example.com/<anything>
RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.example\.com
RewriteRule (.*) http://%1.example.com/$1 [R=301,L]
#
# Redirect example.com/<anything> to www.example.com/<anything>
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Cheers & Happy Coding….