howto: .htaccess redirect to www

In order to redirect all non-www subdomains to your www domain, all you need to do is editing your .htaccess file. I’ll show you how, its pretty easy:

If you want to redirect all non-www requests to your site to the www version, 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 to There are several benefits you’re taking by doing that: You avoid duplicate content in Google and it will avoid the danger of split page rank and/or split link popularity, especially inbound links.

Take care, probably your website has already been indexed by Google without the www, so this lead to a unwanted side effect – lost of your pagerank.
So you might lose it temporarily – that’s why we are using a permanent redirect, a “301”, so Google will transfer all rankings to the www version.

You can use the code snippet above it for any website, since it doesn’t include the domain name.

If you want to redirect reverse, say you want to redirect all www requests to the non-www version, add the following code to your .htaccess file:

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

You see the code is pretty similar, an in this case too, we do not need to explicitly typing the domain name.

You might also have a look at the mod_rewrite Dokumentation of the Apache Project for more detailed information.

2 thoughts on “howto: .htaccess redirect to www”

  1. Facing a problem with my wordpress installation which looks like this:

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    looks like it loops if i put your code into it …?

    • in wordpress you don’t need to rewrite, check the wordpress settings>general URL. All incoming requests will be processed to this one.


Leave a Comment