This is a very simple alternative:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^.*$ https://www.domain.com%{REQUEST_URI} [R,L]
If you want everything to go to www without www, change the last line to:
RewriteRule ^.*$ https://domain.com%{REQUEST_URI} [R,L]
If you prefer to keep www as typed, change the last line to:
RewriteRule ^.*$ https://%1domain.com%{REQUEST_URI} [R,L]
Remembering that if you put the certificate in the same IP of the sites WITHOUT a certificate, and someone trying to access link will give error anyway, because SSL negotiation comes before Apache processes the page.
And that's why SSL-enabled site puts itself in exclusive IP (or if you spend money on certificates for multiple domains).
I took this response from here