Serving website with and wihout “www” prefix

Have you ever thought about a better way of serving website with and without “www” prefix in it’s domain name? I am talking about displaying the same website to your visitors accessing example.com or appending www to it’s name – www.example.com. First of all it’s alway better to serve your website on one domain, there are many reasons to do that, think about cookies which are usually bind to domain name, internal site linkes, cache, etc. But it is definitely good if your website would be accessible even if users will omit www from url, it happends quite frequently. If you are using Apache than my method might be interesting for you.

You have to define ServerAlias with domain name wihtout www prefix within VirtualHost and than redirect users to www.yourhost in case if they got to your site using other domain name, it can be done nicely using mod_rewrite capabilities.

1
2
3
4
5
6
7
8
9
10
11
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
 
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !=www.example.com [NC]
    RewriteRule (.*) http://www.example.com$1 [R=301,L]
 
    // other vhost configuration follows
    ...
</VirtualHost>

One Response

  1. hachik

    I use for apache 1.3 following rewrite condition:

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

Leave a Reply