2010-01-26

Redirect domain.com to www.domain.com

On some websites, a user can access domain.com or www.domain.com -- notice the www. prefix.

The problem is that some search engines may see http://domain.com and http://www.domain.com as separate and consider the content to be duplicate content.

Also, some webmasters prefer users to access the host qualified domain (www.domain.com) rather than just the simple domain (domain.com)

By adding two lines to your website's .htaccess file, you can automatically redirect the user from domain.com to www.domain.com. This redirection works for all files, not just the homepage.

In your root .htaccess file, above all other RewriteRule and RewriteCond statements, add lines like these:

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

Replace domain with your domain. In the RewriteCond, the \ (before the . of .com) is required otherwise the dot would match any character.

So what do these two lines do?

The RewriteCond (a rewrite condition) tests the HTTP_HOST (what domain is being accessed) and compares it to domain.com. If that condition is met, then the next statement is evaluated. If that condition is not met, then the RewriteRule is skipped.

The RewriteRule takes whatever path is being accessed and redirects to that path at the full domain. For example, /something.html would be redirected to http://www.domain.com/something.html

Note: If you have no root .htaccess or it has no RewriteRule statements, then somewhere above the preceding RewriteCond/RewriteRule statements, you also need these two statements to ensure that the Rewrite engine is enabled:

#--- enable Rewrite engine ---
RewriteEngine on
RewriteBase /

So, if you are using one of our DySE scripts, such as DySE::StubHub, then your .htaccess file might look something like this:

#--- enable Rewrite engine ---
RewriteEngine on
RewriteBase /

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

#--- DySE::StubHub at root / ---
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.+$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ cgi-bin/dyse/view.pl?merch=stubhub&dir=&path=$1 [L]

The order of these three blocks of statements is important. You want the test of the domain name to be done before all other RewriteCond/RewriteRule statements.