Remove “www” from site URL with mod_rewrite

I needed to have my gallery URL “www” free, due to some dns problems. So, I searched the Internet and got the solution. If you want you can try this link http://www.nicusor.com/gallery to see it in action. You can find the code for removing and adding the “www” below.

Here is the code to redirect (301) the www version of your site to the non-www version using Apache’s mod_rewrite:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.your-site.com$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://your-site.com/$1 [R=301,L]
</IfModule>

That L flag means Last rule = stop the rewriting process here and don’t apply any more rewriting rules.

Here is the code to redirect (301) the non-www version of your site to the www version using Apache’s mod_rewrite:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com$
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.your-site.com$1 [R=301,L]
</IfModule>

Hope it helps!

Tags: , , ,

Popularity: 32% [?]


1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...

Check out this video!!

Write a Comment

Take a moment to comment and tell me what you think. Some basic HTML is allowed for formatting.

*
To prove that you're not a bot, enter this code
Anti-Spam Image

Type your comment here.

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Reader Comments

Nice little tip. I never thought it made any difference as to whether the www. was actually included or not, is that just the way of telling the browser what protocol you are using with www. being the default?

This is especially good for SEO and some times one or the other may not be configured correctly and not working…

Mod rewrite is also best used to redirect link juice from existing pages to new pages if you decide to rename your pages.

Very useful trick. However, I’ve found another web page with a lot of tricks made just from .htaccess
Here you can find a lot of info about different .htaccess settings: www.perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/ :-)

Thank you for laying this out - I’ve been looking for an easy way to do this for a while now. We usually advise our clients to ask their webmaster to redirect from non-www to www, not the other way around. Any idea why you would suggest one over the other? Consistency is obviously ideal to maintaining link juice.