I have the following in my htaccess to force the www in URLs:
RewriteCond %{HTTP_HOST} !^www\\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] >
RewriteCond %{HTTP_HOST} !^www\\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond is already your "if-condition". Just add another one:
RewriteCond
RewriteCond %{HTTP_HOST} !=localhost RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]