Using the canonical hostname for websites isn't an obvious problem. After all, who really cares if your site is accessible at www.domain.com and domain.com? Search engines, for example, could penalize you for having the same content on both domains. I think that today they are smart enough to discover this specific case though.
Another problem can happen when you use cookies. If not done correctly, your user's cookie won't be available to the website when they were stored under www.domain.com and he uses domain.com the next time he visits. See the cookie specs for more details.
A quick research led me to a solution for apache that I didn't like too much. It involves using mod_rewrite. mod_rewrite is a great tool, but there's a better solution for redirecting to your main domain from subdomains or second level domains. Simply use a catchall virtual host in your apache host configuration file(s) to do the redirects. This will solve all the SEO, caching and cookie issues, and it will save some CPU cycles compared to the mod_rewrite or higher level solutions.
# NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.domain.com
# This is your main domain
</VirtualHost>
<VirtualHost *:80>
ServerName domain.com
ServerAlias *.domain.com
# This is to make sure that foo.domain.com gets redirected too
# If you want to use more virtual hosts on subdomains,
# just define them earlier
Redirect / http://www.domain.com/
</VirtualHost>
Please refer to the mod alias docs to decide which Redirect you need, this example uses a 302.
For lighttpd you can use this:
$HTTP["host"] =~ "domain\.com" {
$HTTP["host"] != "www.domain.com" {
url.redirect = (
"^(.*)$" => "http://www.domain.com$1",
)
}
}
By the way, if you're an IIS user, you might want to read this.
I am Nicolas Kuttler, a web developer, system administrator and IT consultant from France, currently living in Germany.
8 comments
Start a new thread