301 Redirect from non-www to ww -- Without Looping! Print

  • 121

So - you want to improve your search engine rankings, and SEO gurus told you that Google might be penalizing you for duplicate content. How did you get duplicate content, you ask? Unless you specify otherwise, we send www.yourdomain.com and yourdomain.com to the same place. Which is great because some clients automatically add a WWW to every url they type, and others almost never add www even if you tell them to. This way they end up at the correct page, regardless of what else they've included in their url.
The problem is that if people are linking to you sometimes with a www and sometimes without, spiders may think you're trying to get away with publishing the same information twice. So some SEO experts have recommend you create a 301 redirect to send all non-www links to www.
You try it, and to your horror, the page now loops through so many redirect iterations that the site won't display at all. Or, you try the common syntax and it messes up all your subdomains.
There is hope. Here is a 301 redirect syntax that does not loop, and does not affect your subdomains either.

If you're new to 301 redirects, the first thing you want to do is create or edit an existing .htaccess file, which should be in your public_html or web root folder. Add the following lines, substituting your actual domain name instead of the 'yourdomain' and 'com' we list here (in other words, change out the green text)

This one will take you from non-www to www:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(.*)\.yourdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]
Save those changes, and you should now see redirects from non-www to www without looping and without losing your url structure.
If you wanted to redirect the domain EXCEPT for a certain folder, you can use the following;
RewriteEngine On
RewriteCond %{HTTP_HOST} !^(.*)\.yourdomain\.com$ [NC]
RewriteCond %{REQUEST_URI}!/blog$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]
In the above example, the folder that we are NOT wanting to redirect is the "/blog" folder.


Was this answer helpful?

« Back