.htaccess redirect - automatically add www. if no subdomain exists

42,166

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]
Share:
42,166
kdjernigan
Author by

kdjernigan

Updated on July 05, 2022

Comments

  • kdjernigan
    kdjernigan almost 2 years

    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?

  • kdjernigan
    kdjernigan over 11 years
    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!
  • Jon Lin
    Jon Lin over 11 years
    @kdjernigan the www was never added to the redirect, and the first condition matches a subdomain.
  • Kevin Beal
    Kevin Beal over 10 years
    This doesn't appear to work unless it's at the top of my .htaccess file... which is fine. Just strange.
  • jezmck
    jezmck over 10 years
    Does this solution assume a TLD with only one dot? i.e. it won't work for .co.uk?
  • umefarooq
    umefarooq over 9 years
    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
  • LWC
    LWC over 6 years
    TLD assumption aside, how does it know the difference between www and a subdomain? Don't they look the same to the regex?
  • Jon Lin
    Jon Lin over 6 years
    @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.
  • Admin
    Admin over 6 years
    does not work on apache 2.4 - it results in: www.sub.domain.com