To perform a redirect from domain.com to www.domain.com, insert the following code into your .htaccess file.
# mod_rewrite in use
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{http_host} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

To perform a redirect from www site to non-www site, use the following code in .htaccess file.
# mod_rewrite in use
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^domain\.com
RewriteRule (.*) http://domain.com/$1 [R=301, L]

The .htaccess file is simply a text file with the filename .htaccess, and it should be stored at the root directory of your site.

Note, while using .htaccess file, it is important to use it carefully. Wrongly inserted command may render your site not workable.