DamienvanHolten.com

Getting your www rewrite right

Published on May 21st, 2008

It’s not exactly hard, but it can be a life saver. It seems that many developers forget to think about the www, non-www domain request via the browser. I’ve seen big site launches where the www. pointed to the homepage but the non-www gave an error. Keep in mind that a lot of the time with first indexation of the site most search engines point to the non-www domain.

On servers that use Apache you can force every browser request to redirect (with a search engine safe 301 redirect) to www. The following few lines in your .htaccess file will do the trick:

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

Change the above code to your domain and all requests will be rewritten to have the www. prefix. For instance: the request for http://domain.com/directory/filename.html will be rewritten to http://www.domain.com/directory/filename.html.

The .htaccess file

The .htaccess file can be found in the root of your website directory (where you also find your index file). If you can’t locate the file it might be hidden; file names starting with a dot are automatically hidden by a some FTP clients. Set your FTP client to show hidden files.

Another reason for this could be that the .htaccess file doesn’t exist. Just create a new empty file on your server and copy the the above code into it.

Reader Comments (4)

Pål Olsen http://prostuff.org

June 23rd, 2008

That’s true, Damien. It is not a hard thing to fix, but I’m glad you’re getting into it for those who doesn’t have a clue 🙂

Ellen http://lfs.nl

June 25th, 2008

Of course it has to be possible to work with htaccess in the Apache config. The AllowOverride directive is responsible for that. You do have to root-access to enable this. Luckily most configurations are set to all, but i have spend some time over this in particular cases where it didn’t work, and this was the answer.

More information here: http://httpd.apache.org/docs/1.3/mod/core.html#allowoverride

Multiple domain www-rewrite http://www.reaact.net/blog/multiple-domain-www-rewrite/

January 26th, 2009

[…] while ago I wrote about how to rewrite non-www requests to www requests. While that solution is solid and has been working for me the past couple of years I came across a […]

Luke http://www.londonerseye.com

March 11th, 2009

wicked works a treat straight out of the box!

thanks Damien

Leave a comment