ocon --
Anything possible in .htaccess is possible in a server or virtual host context (a few exceptions like RewriteBase). However there are a couple of important differences in the way certain things are handled, especially RewriteRule.
In .htaccess, assuming a RewriteBase of /, the path of a request will
not start with a / -- in a Server or Virtual Host context it will. There are some other differences, in particular with how internal rewriting works (it's far simpler than in .htaccess).
For your case, which is known as domain canonicalization, the example from the Apache Rewriting Guide is designed to handle either context (although it is "wrong" for both!):
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.com/$1 [L,R,NE]
Note the RewriteRule pattern -- ^/?(.*) -- the first character, a / is not required for the pattern to match (that's what the ? does). So, in either context this will work, but I would argue that in a VirtualHost context, this is a better version:
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.example.com/$1 [L,R=301,NE]
The rewrite rule is different. I remove the (now) unnecessary test for the optional / -- it will be there, I change the "R" flag to "R=301" which causes the server to send a 301 "Moved Permanently" HTTP response, rather than the default "Moved Temporarily" 302 response. It is technically unnecessary for the regular expression to include the /, but I do this because I think it makes the substitution ("http://www.example.com/$1") a little more readable than ("http://www.example.com$1")
In the server/vhost context you have much, much more control. You can use the RewriteLog directive to help you understand and debug rewriting, and loads of other fun and useful thing also (assuming you are using a <VirtualHost> container, which I highly recommend, rather than putting directives directly in the server config, you'll know the possible hostnames because you specify the allowed values in ServerName and ServerAlias directives.
Have fun!
Tom
[edited by: sublime1 at 12:50 am (utc) on Oct 14, 2010]