Redirecting non-www to www with .htaccess
080227
If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
This will redirect any requests to http://my-domain.com to http://www.my-domain.com. There are several benefits from doing that:
- It will avoid duplicate content in Google
- It will avoid the possibility of split page rank and/or split link popularity (inbound links).
- It's nicer, and more consistent.
Note that if your site has already been indexed by Google without the www, this might cause unwanted side effects, like lost of PR. I don't think this would happen, or in any case it would be a temporary issue (we are doing a permanent redirect, 301, so Google should transfer all rankings to the www version). But anyway, use at your own risk!
Something nice about the code above is that you can use it for any website, since it doesn't include the actual domain name.
Redirecting www to non-www
If you want to do the opposite, the code is very similar:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC]
RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]
In this case we are explicitly typing the domain name. I'm sure it's possible to do it in a generic way, but I haven't had the time to work one out and test it. So remember to change 'my-domain' with your domain name!
Posted in: English, Web, .htaccess
Tags: mod_rewrite, seo

Would you mind explaining exactly what each part of those two lines does? :)
Always been curious.
Sure! The first line sets a condition: only if the condition is true, the second line will be processed. The condition could be 'translated' to: "if the host name doesn't start with www.". The regular expression !^www\. means this:
! = not
^ = start
\. = . (the backslash is the escape character, because dots have a special meaning in regular expressions, and therefore must be escaped)
So !^www\. means "doesn't start with www.".
The second line is the actual rewrite rule: again it uses regular expressions to match certain urls, and then rewrites them to something else. The first part is the regular expression:
^(.*)$
This means: anything! You already know the ^ sign. The (.*) bit means zero or more characters (the dot means any character, the asterisk means zero or more). The final $ means 'end'.
Then comes the bit that says how to rewrite the url:
http://www.%{HTTP_HOST}/$1 [R=301,L]
%{HTTP_HOST} will be replaced by the host name (i.e. dense13.com).
$1 references whatever was matched in the regular expression between the brackets, which in this case is everything.
The [R=301,L] means "inform the user agent that this is a permanent redirect (HTTP 301 code), and don't process any more rewrite rules (if there were any after this one).
If you're not familiar with regular expressions, this might still look a bit abstract, feel free to ask for more details. :)
Mmmh, I need to do some more work on the blog, I don't like how it automatically adds fancy quotes and converts text that looks like a url into a link.
Y si quisieras hacerlo al reves? Que todo lo que sea dense13.com vaya a www.dense13.com ?
Hi Natalia,
I assume you mean how to redirect from the www version to the non-www version. I've updated the post to include that option as well.
If you're curious, the only thing that's new in that code is the [NC], which stands for no-case (I think). That means that the pattern before will be case-insensitive, and thus will match my-domain.com, My-Domain.com, mY-dOMaiN.CoM, etc.
So I got confused because I types www.dense13.com and it sent me to dense13.com so I assumed you were explaining how to do that www to non-www even though the title says the opposite ... yep, I know how that sounds, don't judge :P
That is also why the actual explanation didn't seem to make a lot of sense :lol:
I actually had to change a .htaccess file without having a clue about the whole thing and somehow made it work, I seem to have some inner intuition that lets me do things my brain doesn't quite grasp.
Minor thing...Comments in reverse order are kind confusing, with posts it works cos one doesn't follow from the previous one, or if it does they are normally linked, comments on the other hand...especially long ones...one has to keep scrolling up and down to follow the conversation if you know what I mean.
You're right, dense13.com uses the www to non-www method, which is confusing, good point. I might reverse the order of the two methods in the post, to avoid confusion.
I kind of like reversed order also in comments, mmmh, I'll have to think about that one.
Wo-hoo! I managed to disable curly quotes and auto-links in comments! :)
Hi, Great tutorial, thanks. Also, thanks for taking time to explain
what exactly each of those symbols meant :) One question. After
using the non-www to www redirect, it redirects my site to the www
version just fine. But the thing is, if I enter in
site.com/somepage.html , it redirects me to www.site.com and not
www.site.com/somepage.html. Is there any way to make it do the
latter? Thanks in advance :) Nithanth
Hi Nithanth. That's strange, it should be redirecting you to the right page. First thing would be to make sure you typed the right code in your .htaccess, which you've probably done already. Feel free to paste your htaccess code here or mail it to me at gperezdelaossa_AT_dense13_DOT_com . I don't know if I'll be able to help, but I can try. :)
Hi, This is how my htaccess currently looks: [code] # -FrontPage-
IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*
order deny,allow deny from all allow from all order deny,allow deny
from all AuthName nithanth.net AuthUserFile
/home/nithanth/public_html/_vti_pvt/service.pwd RewriteEngine On
RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond
%{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteEngine
On RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$
http://www.%{HTTP_HOST}/$1 [R=301,L] [/code] Site is nithanth.net.
Try http://nithanth.net/general/hello-world/ - it doesn't take me
to http://www.nithanth.net/general/hello-world/ , instead it takes
me to http://www.nithanth.net/index.php :(
Mmh, I'll have to offer a way for people to post code, it's all messed up, sorry! I'll try to re-format it, and have a look. I might not be able to do it straight away though, I'm going through a bit of a busy period right now, but will let you know when I do.
The code works perfectly, thank you.
thanks for the code, it's all that i need
Unfortunately this method messes up SSL URLs. https://my-domain.com
gets redirected to: http://www.my-domain.com Not good. :(
You could create a second .htaccess file in the folder(s) where your SSL pages are, using replacing http for https. I haven't actually tried this, but I'd say it should work.
Actually just add this line to the conditions: RewriteCond
%{SERVER_PORT} ^80$ Assuming all your http traffic is on port 80
this will do the trick.
Oh and do a separate condition/rule for port 443 (SSL)
That's neater, good thinking.
Great tip, thanks! No more putting full domain name in the
.htaccess file :)
Thanks very much for this post. I created a .htaccess file with
your code copy-pasted for website www.limlum.com. When I type
limlum.com in the web browser address, it redirects to
http://www.limlum.com/public_html/ which does not exist and I get a
404 error. Am I missing another file on the webste?
RewriteEngine On RewriteCond %{HTTP_HOST} !^www\\.RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Sorry I posted before testing properly - I put the .htaccess file
in a directory one level above public_html which is the wrong
location. I put it in public_html and it now works. Thanks.
Bro, what about having subdomains? I used your code but now this
code is forwarding my subdomain to a www site as well. So how do
you add an exception to the code for a subdomain?
Nice code. Works fine but what about if someone is running
subdomains? The code forwards my forum sub domain to www.forum. ...
etc. So how can I add an exception to the code not to touch the sub
domains?
@Asak Kay: just change the Rewrite condition to include any other subdomains besides www:
RewriteCond %{HTTP_HOST} !^(www|sub1|sub2)\.That should do it.
I's supposed you will need to write RewriteRule ^(.*)$
http://www\.%{HTTP_HOST}/$1 [R=301,L,NC] instead of RewriteRule
^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] I'm add /. and NC, nc
here for no case option, so you can write your domain in any case
Am I correct?
@nyha: I dont think you need to escape the period in the second part of the RewriteRule, that's not a regexp. And not sure about the NC, I think that's to use in the condition (as in 'Redirecting www to non-www' in the post). But might be worth testing, I'll see if I can do it some time soon.
Really nice explanation for redirect condition.
Thanks for this post. Having just changed webhosts and the new one
not offering a GUI for updating the www to non-www redirect and
thanks to GOOG I've landed here and am now learning the basics of
.htaccess editing (secretly, it tickles the geek in me :) Thanks,
also, for explaining the entry. As easy as it is to just cut and
paste something I, personally, prefer to understand how to do it.
Although I think I'll have to re-read it a few more times first.
Once again, cheers. :)
Thank you so much for this post !! I had the same problem as Asad
Kay (in comment nr.24) with the sub domains and your solution (in
comment nr.25) was a life saver for me !! It's very simple when you
think about it, but I didn't and was struggling with it for half a
day !! Thanks again !!
Great post, thanks a lot!! I had an error in my code and could not
figure out why I got an interal server error until I found this
post. Just copied the code and pasted into my htaccess and it works
perfectly. Again, thanks for the post :)
Thank you for this great post.Finally found what i need to redirect
all of my pages non www to www.Really helpful!
Thanks for help!!!!!!!!!!!!!!
[...] For non-www to www [...]
Hi, What is better for SEO www to non-www or non-www to www? I have
read that one way if good for SEO but the other not. What is the
best way? Thanks
@Laurent: I don't know, you'll have to look for some SEO specific resource. I suspect it won't make any difference, but that's just my intuitive opinion.
Hi, I would like to use mod rewrite to redirect domain-N.tld to
www.domain-N.tld (1.) sub-M.domain-N.tld to sub-M.domain-N.tld
(keep the original, don't add www). (~ if the request is domain.tld
-> rewrite, else keep) I have over 100 domains, so N,M>100,
and I need regexp. (1.) works fine, but I can't remove the www from
the subdomains. If you can, please help me. Thx.
Thanks so much for the right code for non-www to www. I have been
trying for a week to get my site to redirect. I have searched many
sites for advice, but unfortunately nothing worked until I put your
code in. I added [NC] after "RewriteCond %{HTTP_HOST} !^www\.
[NC]". Works great! Thanks again.
Hi, I would like to use mod rewrite to redirect
mysite.com/index.php to www.mysite.com ,but I can't ! If you can,
please help me. Thank's...
Hello, thanks for your excellent site. Perhaps you can help with my
problem. Any help is appreciated! I want to redirect my /index.html
to my "/" (www.sample.com). There is only one domain on the server.
I am using the following script: RewriteEngine On RewriteCond
%{THE_REQUEST} /index\.html\ HTTP/ RewriteRule ^index\.html$ /
[R=301,L] It works, but if you type other things in your browser,
it brings up a webpage but without all the shapes/pics/etc. For
example: www.sample.com/paper/index.html would bring up the webpage
www.sample.com/paper with the text, but without the shapes, pics,
etc. I want the .htaccess to redirect those types of requests to
the www.sample.com/ page (and of course, without the .index.) I
tried: RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\
/(([^/]+/)*)index\.html\ HTTP/ RewriteRule index\.html$
http://www.example.com/%1 [R=301,L] It works about the same as the
first example.
very nice solution through .htacess. I was looking for some plugin
for to do the job of shifting www to non www
Very helpful... I was able to redirect my main blog but unable to
redirect the addon domain to www version.
[...] pour n’importe quel site, puisque le nom de domaine n’est pas
dedans.Via : Redirecting non-www to www with .htaccess Image via :
DatacenterArticles RelatifsFaire détecter son Eee par sa Freebox3
commandes à ne pas [...]
Thank you! Someone gave me the opposite code! >:(
Hi there, What code do i need to program to redirect ONLY
http://mydomain.com to http://www.mydomain.com i tested the first
one in this topic and it went good but it went wrong when i
navigate to my ssl url https://secure.mydomain.com can anyone help
me with this?
@MiC: check out comments 15 to 17. Try what John M suggests in 17, I haven't tested it myself but it should work.
Hi, I got a queriy and wanted your help in this regard. When people
access my domain it is redirected to
http://www.mydomain.com/en/index.php file using php code.I used
RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$
http://www.%{HTTP_HOST}/$1 [R=301,L] to redirect people from non
www to www but its not working. Still user can access
http://mydomain.com/en/index.php
@Anand: that code should work, there might be other parts of your .htaccess file influencing it (assuming you are using an .htaccess file). I suggest commenting things out and make sure the redirection is working correctly, and then bring things back step by step, to locate the problem. You might also want to post to a forum, including your .htaccess code (I'm keen to help when I can, but have limited time).
Hi My rule for redirecting making flat links works, but how do i
combine the two rules please?? RewriteEngine on RewriteRule
^page/([a-z]+) home.php?page=$1 [NC] RewriteCond %{HTTP_HOST}
^domain\.co\.uk [nc] RewriteRule (.*) http://www.domain.co.uk/$1
[R=301,L]
@MartynG: first do the www redirection, then send everything to home.php.
hi dense13, can you tell me if your code to redirect(non-www to
www) will work on an iis6 server without using any kind of plugins
or other installations (ie. heliotech - isapi rewrite)? our pages
are coming from an apache server to the iis6 server. thank you
@cyndi: I don't think so, but I don't know much about IIS.
can you help me to resolve the error at
http://www.kerjatop.com/sitemap.xml otherwise but there is no error
with http://kerjatop.com/sitemap.xml
@heru: what redirection are you using? What are you trying to do exactly?
Excelent it works to me, i was lookin' all over internet, and i
finally get! It's a got idea to redirect to only one page!
Thanks so much! What a life-saver.
Thanks so much, looking for this for ages :D
Question concerning non-www to www. I have a site in which a
discussion forum resides in one of the sub-directories. The
standard rewrite plays havoc with the Forum but I still want to use
the redirect on the root directory only. Is it possible rewrite
non-www to www for the root directory only? Exclude rewrites for
sub-directories?
How to add the code in the wordpress installation? my site got
error when adding the code. # BEGIN WordPress RewriteEngine On
RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond
%{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L] # END WordPress
Perfect formula, since it's generic!
Working for me! Thank you very much!
Thanks for nice post. I've implemented this on my web. It redirect
from mydomain.com to www.mydomain.com. but when I try to open
directly from URL: mydomain.com/somedirectory/somepage.htm it still
not redirected to www.mydomain.com/somedirectory/somepage.htm Can
you help me how it could redirected as well?
I've tried this method but i was still confused use this in another
directory..
Hi this is my .htaccess file in joomla and sends people to my new
site and it also redirects www to non www it works fine but how do
I make a permanent (301) Redirect RewriteEngine on RewriteCond
%{REQUEST_FILENAME} !-f RewriteRule ^(.*)index.shtml$
http://www.mynewsite.com/index.php RewriteRule ^/(.*)$
http://www.mynewsite.com/index.php
Hey, just wanted to say thanks! After reading over many tutorials
on how to go about this I wasn't fully understanding the method
(many kept trying to input URL's as well and I needed a generic
method). This worked flawlessly, :).
Hello, Thanks for your tutorial. It's working fine. But I need my
site to be redirected to ROOT for all version of index.php. For
example if I type http://www.grantmarketinggroup.com/index.php it
will be redirected to http://www.grantmarketinggroup.com/ . I have
tried lots of rewrite rules but no results. Hope you will find time
to respond me. Thanks again. Gowranga
thanks brooo
I'm having issue while trying to redirect non www to www in
wordpress. it gives redirect loop errror :(
It would be great if you can also create an IIS version for non-www
to www redirection. Not everyone uses Apache as a web server.
when I do this, all I ever get is an endless browser redirect
warning (i'm using WordPress also): I have this: #non-www to www
start RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. RewriteRule
^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] #non-www to www end #
BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule
^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond
%{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END
WordPress any ideas??
after creating .htaccess with above information to convert www to
non www my site traffic decreased to 50% in 1 day and in webmaster
page index its showing pending. i have undo the changes still i
cannot see any change in traffic its going on decrease..any idea
again when my results will be normal in google ?
Sorry renuka, I can't help with that. I'd go to a SEO-specific forum and ask there. I hope you can sort that out quickly.
Thank you so very much for this information and thorough
explanation on how to redirect www to non-www and vice-versa with
htacess. I don't have subdomains so far, but I thought I'd
implement the line on Comment #25 just in case. But when I changed
RewriteCond %{HTTP_HOST} !^www\.into RewriteCond%{HTTP_HOST} !^(www|sub1|sub2)\., the redirecting stopped.
Redirecting resumed as soon as I switched back to the original
line. Any ideas why? Should I have added the line in Comment #25
instead of substituting? Thanks.
very nice solution through .htacess.
Wondering if it's possible to redirect a website folder link that
comes before another one - so, redirecting without effecting any
further sub folders links? For instance, I have a page called
"www.xxx.com/abc/1" But I don't use /abc/ folder anymore and want
to redirect it to /def/ folder instead. So, www.xxx.com/abc/
redirects to www.to xxx.com/def/ But when I create a .htaccess with
the codes below; URL PERMANENT REDIRECT Redirect permanent /abc
http://www.xxx.com/def Then, abc/1/ folder also wants to redirect
to /def/1/ Since there is no page called def/1/ on my server and no
chance to create/move the page due to some complexities, how do you
think I can resolve this issue with .htaccess? Thanks.
Sorry about all the people asking for help, I'd like to help out but I don't have much time available now. I will try to find some, but can't guarantee...
Great post... thanks for sharing! I am having a problem with this
and was hoping you could give me a steer in the right direction.
When I upload the .htaccess file and then enter in the url without
the URL e.g website.co.nz the browser is redirecting to
www.website.co.nz/www/htdocs/ I cannot work out where it is picking
up the /www/htdocs element from. Can you shed any light?
Add a comment