Blog

Using htaccess to add or remove the WWW from URLs

Posted on November 10, 2009 Posted in blog, web development
Using htaccess to add or remove the WWW from URLs

Sometimes you want to make sure that your website is accessed through a consistent URL. And I am always looking around for the piece of code used in the htaccess file that either removes or adds the ‘www’ to the URL domain.

As I am always referring to it, I thought I’d add it here to help me and help others who may find it useful.

The htaccess configuration file is very powerful and what’s covered here is just the tip of the ice-berg.

These settings are for an Apache server but there’s also a way to use this in a Windows IIS setup with ISAPI being enabled.

Let’s get started.

Create a file named ‘.htaccess‘ and edit it with Notepad.
If you want to remove the www from all your URLs then add the following code to your file:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

Or, if you want add the www to all your URLs then add the following code to your file:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www.yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

Then place the .htaccess file in the root of your web folder or whichever folder your domain points to and it should work.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to StumbleUpon

3 Comments »

    • November 18, 2009

      I only wanted to say thanks for all the great info found on your blog, even helped me with my job recently :) keep it up!

    • November 18, 2009

      Glad it helped, thanks for the comment.

Leave a reply

Your Name
July 14, 2009

Name

Mail (will not be published)

Website

Message

* Name, Email, and Comment are Required