Jon Simpson’s Weblog

My personal space for ideas & information.

301 redirect non-www to www

In continuation of the theme ‘using my blog as a personal notepad’, here’s a small snippet for use in an Apache .htaccess file to ensure that visitors/incoming links not using the www. form of your site’s domain are redirected correctly.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.co\.uk
RewriteRule (.*) http://www.example.co.uk/$1 [R=301,L]

Make sure to escape periods in the RewriteCond line with backslashes. Reasons you might wish to do this mostly relate to search-engine friendliness and unity of web stats.

Previous: Wordpress with Subversion: Upgrades Next: On robotics abstractions (or how robots can’t take over the world, yet)

7 Comments

  1. Paul Findlay says:

    What would the reverse of this be? i.e. if you wanted to send all visitors to http://www.example.co.uk to http://example.co.uk

  2. Michael Benson says:

    You’d have to use;

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

  3. Yan says:

    Thanks for the tip. Just did it on my sites. Was losing a lot of backlink juice because some would bookmark as www, while some w/o it.

  4. Art says:

    Thanks for the tip, i have used it on my paintings site to redirect the non www url to the www url.

    thanks :)

  5. Lior says:

    Will that work for all pages, or just the home page?

    I did it, and the only redirect I got is from http://domain.com to http://www.domain.com

    But not from http://domain.com/page.html to http://www.domain.com/page.html

    ??

  6. Huskey says:

    The correct (and complete) form to use for non-www to www is:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^domain\.com [NC]
    RewriteRule ^(.*) http://www.domain.com/1 [R,L]

    Similar, for www to non-www:

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

    The $ sign marks a line end, therefore your rule will never trigger for a http://domain.com/something page.

  7. Huskey says:

    Sorry for double post. http gets translated to a link and deletes the $.

    RewriteRule ^(.*) http://domain.com/1 [R=301,L]

Leave a Reply