Here's the complete library for use in .htaccess:
# Redirect if NOT www.example.com (exactly) to www.example.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
-or-
# Redirect if example.com (case-insensitive) to www.example.com
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
If you want to do the opposite, i.e. redirect www to non-www
# Redirect if NOT example.com (exactly) to example.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]
-or-
# Redirect if www.example.com (case-insensitive) to example.com
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]
All differences between this and what you posted are intentional. Select the code snippet that matches your needs. Note that using the "NOT " versions precludes the use of subdomains other than "www", but is more comprehensive.For use in httpd.conf, change the rule pattern from "(.*)" to "^/(.*)".
If the non-canonical www domain already works --that is, if it returns the same content as the non-www domain-- then no changes to your ServerName/ServerAlias configuration are necessary.