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