How to use URL rewriting to control access to www

January 29th, 2009 | Tags: , , , ,

Having your site respond with content to requests on both domain.tld and www.domain.tld can give the appearance to search engines that your site has duplicate content, so don’t do it. Here’s how:

Using Apache and mod_rewrite or IIS and ISAPI_rewrite 3:

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

Using IIS and ISAPI_rewrite 2:

RewriteCond Host: (?!^www\.domain\.tld).+
RewriteRule ^/(.*) http\://www.domain.tld/$1 [I,RP]

To force the domain to be without the www, just remove the “www.” and “www\.” portions from the rules.

For Apache, I prefer to use name-based virtual hosts and have the redirect site be a different host. To do this, you define one virtual host that matches any domain you want redirected to your canonical domain and then one virtual host for your canonical domain:

Listen 80
NameVirtualHost *:80

<virtualhost *:80>

    ServerName domain.com
    ServerAlias domain.net
    ServerAlias www.domain.net
    ServerAlias domain.org
    ServerAlias www.domain.org

    RewriteEngine On
    RewriteRule ^/(.*) http://www.domain.com/$1 [L,R=301]

</virtualhost>

<virtualhost *:80>

    ServerName www.domain.com

    # all other site settings go here

</virtualhost>
No comments yet.

TOP