How should I configure multiple virtual hosts with a single configuration file in Apache?

Solution 1:

In addition to the proposed duplication here are few answers specific to this question:

How do I setup HTTPS virtual host with ServerAlias in use.

If you are using ServerAlias directive within HTTPS/SSL virtual host you need to issue certificates for all domain names. By using letsencrypt you will need to add few -d options:

sudo letsencrypt --apache .... -d www.example.com -d example.com

All certificates will be placed in the same certificate file.

Is it possible to make whole configuration to one file, especially one VirtualHost? I have 2 files now, one for 80, second for 443.

You can place the definitions for all VirtualHosts in one file, thus it will be easy to enable and disable all of them together. But there is no way to configure one VirtualHost to listen on two ports.

What about Redirect instead Rewrite in ssl config?

According to Apache2's documentation for such cases it is better to use the Redirect directive instead of Rewrite rules. Note, you need to create two separate VirtualHosts if you want to redirect https://example.com to https://www.example.com. All related VirtualHosts can use the same certificate file, generated in the way described above.

Each virtual host will be responsible for a different ServerName, for example: ServerName example.com for the first, respectively ServerName www.example.com for the second, etc. Note the ServerAlias directive must be removed.

If everything works as expected, you can keep using Rewrite rules - this is subject of your decision. If you are using Redirect directive, do not miss the slash at the end of the target domain name! Here is an example for HTTPS VirtualHost that uses the Redirect directive.

<VirtualHost *:443>
    ServerName thehatmakers.cz
    Redirect permanent "/" "https://www.thehatmakers.cz/"

    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/hosek/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/hosek/privkey.pem
</VirtualHost>
  • You do not need anything else for this VirtualHost.

  • The keyword permanent will instruct the client's browser to do this redirection automatically next time.

  • Redirect = HTTP 302

  • Redirect permanent = HTTP 301