19

I need any www. added automatically to my domain ONLY IF a subdomain is not already there. I do want subdomains to bypass this redirect.

How can I do this?

Dharman
  • 21,838
  • 18
  • 57
  • 107
kdjernigan
  • 407
  • 2
  • 6
  • 22

1 Answers1

66

To automatically add a www to your domain name when there isn't a subdomain, add this to the htaccess file in your document root:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
Jon Lin
  • 135,941
  • 26
  • 200
  • 209
  • Thank you. This seems to work. Can you explain why the previous one didn't work in your opinion? I noticed it working; however, then noticed that my subdomain didnt work. Not sure if this was related or not or just propagation issues. I would love to learn more about what each line means of the 2 answers. Thanks! – kdjernigan Sep 04 '12 at 07:54
  • @kdjernigan the `www` was never added to the redirect, and the first condition matches a subdomain. – Jon Lin Sep 04 '12 at 07:56
  • This doesn't appear to work unless it's at the top of my .htaccess file... which is fine. Just strange. – Kevin Beal Sep 26 '13 at 04:41
  • 5
    Does this solution assume a TLD with only one dot? i.e. it won't work for `.co.uk`? – jezmck Oct 11 '13 at 11:12
  • 1
    its checking only one dot in TLD to make it work with .co.uk you need to check two dots here is my quick solution RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+\.[^.]+$ just change this condition rest remain same – umefarooq Jan 28 '15 at 06:14
  • TLD assumption aside, how does it know the difference between www and a subdomain? Don't they look the same to the regex? – LWC Aug 27 '17 at 20:31
  • 1
    @LWC the regex is only checking the domain and TLD, it won't know the difference between a "www" or any other subdomain. Thus if there is a subdomain, or a "www", the condition fails and the rule is skipped. – Jon Lin Aug 28 '17 at 03:02
  • does not work on apache 2.4 - it results in: `www.sub.domain.com` –  Jan 16 '18 at 15:52