1

I need to force WWW on my website.

So I used this htacces:

#Redirect non-www to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Problem is that http://subdomain.mydomain.com will be redirected to http://www.subdomain.mydomain.com

How do I fix that?

AMadmanTriumphs
  • 4,888
  • 3
  • 28
  • 44
456543646346
  • 973
  • 4
  • 15
  • 22

2 Answers2

2

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]
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
1

If you want to redirect only the main domain

RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule .* http://www.%{HTTP_HOST}/$0 [R,L]

Never test with 301 enabled, see this answer Tips for debugging .htaccess rewrite rules for details.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198