Canonical Urls With Mod Rewrite

| | Comments (1)
It's not unusual to have multiple domains pointing at one site, possibly for brand protection or vanity domains.

If these extra domains are simply added in as aliases of the main domain, they will all appear as separate sites to search engines such as Google or Yahoo. This means that the various domains probably incur a duplicate content penalty.

Fortunately, this is easy to get around. Presuming that your primary domain name is example.com, the following can be put at the top of the .htaccess file in your document root:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
The RewriteCond line checks to see if the HTTP_HOST¹ is NOT example.com. If this is the case it will do a permanent(301) redirect to http://example.com/$1, where $1 is the part that was after the HTTP_HOST.

As written above, example.com will appear as the canonical url rather than www.example.com. If the user does enter www.example.com, they will get redirected to example.com. To change this behavior, add in the www in the third line.

¹HTTP_HOST is the domain name that the user is using to access the site  when the .htaccess file is called by Apache.

1 Comments

Ricky said:

Thanks for such a great post.

But do these redirection modules work on all platforms. I have a windows based hosting and I tried this module on it but it is not working. Can you please tell me if it works on all platforms and if not then can you please guide me in creating 301 redirects on windows based hosting panels.

Leave a comment

About this Entry

This page contains a single entry by Niall Donegan published on October 3, 2007 9:00 AM.

Making the most of Apache was the previous entry in this blog.

Blocking Specific User Agents is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.25