Forcing hostname in Apache-based websites

August 5th, 2007
Assume that you have a website, name it www.website.com. Because users tend to omit the www. prefix when typing a URL, it's reasonable that you want any requests to website.com to be served as well, instead of returning a 404 Not Found error. Obviously, you think you just have to add a ServerAlias in your virtual host's configuration, and you are right. But, that's only half of the story.

By only adding a server alias, you ensure that misspelled URLs are served, but you leave no clue to the client to let her know that the URL is deprecated. You can solve this by using Apache's rewrite module. Make sure that you have enabled mod_rewrite in your Apache web server and add the following in the apache's configuration file (inside your <VirtualHost> section is a good spot):

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


The code above will force all requests with a hostname other than www.website.com to be redirected to http://www.website.com, retaining the path-part of the URL. The client will be redirected using a 301 HTTP response code (Moved Permanently), which informs the client that the URL is not valid any more, and encourages her to update any bookmarks or permanent links to this page.

Leave a Reply