HOWTO - Fix Canonical Problems with .htaccess and mod_rewrite

by Chris Olstrom

in HOWTO

Canonical problems occur when there is confusion over which version of a given document is ‘official’.

If a URI identifies a specific document, two different URIs are often treated as two different documents. If the contents of each are identical, it could be assumed that one is a copy of the other. In fact, if we treat them as two documents, that is the only logical conclusion. How then, if both are truly identical in all ways other than URI (same timestamps, content, etc), are we to determine which is official?

This is a canonical problem, and it can be fixed using mod_rewrite.

The most common type of canonical problem occurs when search engines recognize www.yourdomain.com, and yourdomain.com as different sites. A quick fix can be implemented in your .htaccess file like so (using mod_rewrite):

Enable mod_rewrite if it is not already active:


RewriteEngine On

And set up a rule to direct the unofficial (non-www in this case) to the official (www) with a status code indicating that this is a permanent redirect (HTTP 301).


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

This tells browsers and search bots that the canonical (official) URL for your site is the one with www, and that all requests should be directed there.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google