Redirect to HTTPS – How to Redirect to HTTPS for Multiple Subdomains Configured as ServerAlias

Apache2

I have installed SSL via certbot and all my sites can be accessed via SSL.

However, when http is used in the browser url, only the 1st one from below gets redirected to https. The others don't get redirected to https and continue to be in http.

  1. mydomain.com
  2. xx.mydomain.com
  3. yy.mydomain.com

For port 80, below are contents of the rewrite logic in virtualhosts file:

RewriteEngine on
RewriteCond %{SERVER_NAME} =mydomain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

For port 443, below are the contents of the virtualhosts:

DocumentRoot /var/www/html
ServerName mydomain.com
Include /etc/letsencrypt/options-ssl-apache.conf
ServerAlias xx.mydomain.com
ServerAlias yy.mydomain.com
SSLCertificateFile /etc/letsencrypt/live/yy.mydomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yy.mydomain.com/privkey.pem

As you will see, the domain and subdomains point to the same document root directory.

How to make all urls listed in the above points to redirect to https when http is entered in browser? I am not sure what exactly needs changing in the port 80's rewrite logic to make this work for sub-domains configured as server aliases.

Best Answer

Your configuration is conditional (on the request being made to =example.com) therefor the RewriteRule won't redirect for requests to xx.example.com.

You can either

  • improve that condition (when you still want to only redirect for specific (sub-) domains). Not very beautiful but for example:

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =example.com     [OR]
    RewriteCond %{SERVER_NAME} =xx.example.com  [OR]
    RewriteCond %{SERVER_NAME} =yy.example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    
  • remove the condition completely (and redirect everything to https (with the risk that you also redirect new-subdomain.example.com to https for which you don't have a valid certificate yet)

    RewriteEngine on
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]