Apache2 with SSL do I have to copy VirtualHost blocks?

Solution 1:

You can't make one vhost do both HTTP and HTTPS, because they are separate vhosts servicing separate protocols. Instead, you should put all of the common configuration into a separate file, and then include that file in both the SSL and non-SSL vhosts for the domain.

Minimal example:

# /etc/apache2/sites-available/example.com
<VirtualHost *:80>
  Include /etc/apache2/domains/example.com
</VirtualHost>

<VirtualHost 192.0.2.1:443>
  SSLEngine On
  SSLCertificateFile /etc/ssl/example.com_crt
  SSLCertificateKeyFile /etc/ssh/example.com_key

  Include /etc/apache2/domains/example.com
</VirtualHost>

# /etc/apache2/domains/example.com
ServerName example.com
ServerAlias www.example.com

ServerAdmin [email protected]
DocumentRoot /home/example/public_html
ErrorLog /home/example/apache/error.log

Solution 2:

As I mentioned on a different question on stackoverflow (https://stackoverflow.com/questions/679383/do-i-have-to-duplicate-the-virtualhost-directives-for-port-80-and-443/52375167#52375167):

Another option instead of using Include is using Macro (so you can keep it all in one file).

First enable the macro module:

a2enmod macro

Then put your shared stuff in a macro and use it from your virtualhosts:

<Macro SharedStuff>
   ServerName example.com
   ServerAdmin [email protected]
   <DocumentRoot /var/www/example>
      ...
   </DocumentRoot>
</Macro>

<VirtualHost *:80>
  Use SharedStuff
</VirtualHost>

<VirtualHost *:443>
  Use SharedStuff

  SSLEngine On
  SSLProtocol All -SSLv2 -SSLv3
  ...
</VirtualHost>

Macros can also take parameters, and be defined in other files that are included; so you can use them a bit like Functions, and save a lot of duplication across your Apache config files.

See here for more details:

https://httpd.apache.org/docs/2.4/mod/mod_macro.html