Apache redirect non www to www using .htaccess

Its ok to allow users to access your website using www and non www address but for consistency and SEO considerations its desiratble to use one version. If you are using apache web server this can be achived by using htaccess file.

Non Www To Www

301 re-write rule in your .htaccess file so that both addresses (http://example.com and http://www.example.com) resolve to the same URL.

If you want to redirect http://www.example.com to http://example.com, you can use this:

RewriteCond %{HTTP_HOST} ^www.example.com$  
RewriteRule ^/?$ "http://example.com/" [R=301,L]  

If you want to redirect http://example.com to http://www.example.com, you can use this:

RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]  
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]  

Http To Https

RewriteEngine On  
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Please note this can be used when you are using apache webserver and this is not recommended if you are using nginx. IF you wan to try it using nginx please see post
how to redirect non www to www for nginx