Apache webserver: How to redirect all requests to domain.com to www.domain.com [duplicate]

Solution 1:

I personally have always found a simple 301 redirect to be more than adequate for this purpose:

<VirtualHost *:80>
    ServerName  oakalleyit.com
    Redirect    301 /   http://www.oakalleyit.com/
</VirtualHost>

It's simple, easy to read/remember, and get's the job done right.

This is actually copied from my production web server, so I know it works.

There are docs on Apache redirects available here: http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect

And I just tested, and typing http://oakalleyit.com/user redirects correctly to http://www.oakalleyit.com/user

Solution 2:

I always use a negated pattern, so anything that matches the Virtual Host, but doesn't match the canonical address, will be redirected.

RewriteCond %{HTTP_HOST} !^www.example.com [nocase]
RewriteRule ^/(.*)$ http://www.example.com/$1 [redirect=permanent,nocase,last]

This has the benefit of an unlimited and unspecified number of ServerAlias directives (eg, *.example.net, *.example.org, *.example.asia etc) to all redirect correctly to www.example.com)