'Wildcard SSL vhosts configuration with RewriteEnginer

I am currently working to configure a domain that has many wildcard subdomains. I want to make sure the following occurs.

  1. All *:80 traffic gets translated to the corresponding fqdn domain name in HTTPS

For Example:

http://jane.example.com -> https://jane.example.com

http://jack.example.com -> https://jack.example.com

http://www.example.com -> https://www.example.com

A couple caveats:

A. my ssl cert is a wildcard, so if there is no host, I want to make sure the redirect includes a host of www. both on *:80 and *:443

http://example.com -> https://www.example.com

https://example.com -> https://www.example.com

The vhost looks like:

<VirtualHost 108.161.x.x:443>
    Servername %1.example.com
    ServerAlias www.example.com
    DocumentRoot /home/sites/example.com/www
    ErrorLog logs/md-ssl-error_log
    CustomLog logs/md-ssl-access_log common
       SSLEngine on
       SSLCertificateFile /etc/ssl/kl_crt.crt
       SSLCertificateKeyFile /path/to/kl_pk.key
       SSLCertificateChainFile /path/to/kl_cab.crt

  RewriteEngine On
  RewriteCond %{HTTPS} off [OR]
  RewriteCond %{HTTP_HOST} ^www\. [NC]
  RewriteCond %{HTTP_HOST} ^?(.+)$ [NC]
  RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</VirtualHost>

The regular http traffic here

<Virtualhost 108.161.x.x:80>
  ServerName %1.example.com
  RewriteEngine On
  RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</VirtualHost>

Anyone know whats wrong with my code?



Solution 1:[1]

You can try something like this :

ServerName example.com
ServerAlias %1.example.com
  
DocumentRoot /home/sites/example.com/%1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashitaka