Apache Redirect for http to https via .htaccess

Generic way to do it but would result into duplicate URLs, e.g. https://example.com & https://www.example.com

1RewriteCond %{HTTPS} off
2RewriteCond %{HTTP:X-Forwarded-Proto} !https
3RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

To avoid the duplicate URLs, do the following:

 1## 1. Redirect all non-https except www to https://www
 2RewriteCond %{HTTP_HOST} !foo\.example\.com [NC]  # exclude foo.example.com domain
 3RewriteCond %{HTTP_HOST} !bar\.example\.net [NC]  # exclude foo.example.net domain
 4RewriteCond %{HTTP_HOST} .
 5RewriteCond %{HTTP_HOST} !^www\. [NC]
 6RewriteCond %{HTTP:X-Forwarded-Proto} !https
 7RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 8
 9## 2. Redirect for http://www to https://www
10## NOTE: HTTP_HOST already starts with "www" (e.g. www.example.com) so it's no longer
11## hardcoded in the RewriteRule. Otherwise, it would become www.www.example.com which 
12## is clearly wrong.
13RewriteCond %{HTTP_HOST} !foo\.example\.com [NC]  # exclude foo.example.com domain
14RewriteCond %{HTTP_HOST} !bar\.example\.net [NC]  # exclude foo.example.net domain
15RewriteCond %{HTTP_HOST} .
16RewriteCond %{HTTP_HOST} ^www\. [NC]
17RewriteCond %{HTTP:X-Forwarded-Proto} !https
18RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
19
20## 3. Redirect all https to https://www except those https://www
21RewriteCond %{HTTP_HOST} !foo\.example\.com [NC]  # exclude foo.example.com domain
22RewriteCond %{HTTP_HOST} !bar\.example\.net [NC]  # exclude foo.example.net domain
23RewriteCond %{HTTP_HOST} .
24RewriteCond %{HTTP_HOST} !^www\. [NC]
25RewriteCond %{HTTP:X-Forwarded-Proto} https
26RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

See https://www.drupal.org/docs/7/modules/domain-access/htaccess-changes-optional for some other examples.