Do I have to duplicate the Virtualhost directives for port 80 and 443?

Viewed 60694

I have a long and intricate list of <VirtualHost> directives, and I have to duplicate them into separate <VirtualHost> groups for ports 80 and 443 because I'm using SSL. Whenever I update my mod_rewrite rules I have to remember to do it in both places or else I'll break my app... this duplication is asking for trouble. Is there a way to combine or alias these -- the only difference between the two is that the port 443 version contains the SSLEngine, SSLCertificateFile and the like.

My <Virtualhost> contains many mod_rewrite rules, LocationMatch rules, CGI directives, etc.

Also, I can't use .htaccess files.

6 Answers

Can't you use an include directive to include the common rules. here

article

eg.:

<VirtualHost _default_:80>
    ...
    include conf/common_rule.conf
</VirtualHost>

<VirtualHost _default_:*>
    ...
    include conf/common_rule.conf
</VirtualHost> 

<VirtualHost _default_:443>
    ... #SSL rules
    include conf/common_rule.conf
</VirtualHost>  

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 example@example.com
   <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

You could put the common configuration into a separate file and include it in both VirtualHost segments. For example:

<VirtualHost 192.168.1.2:80>
  Include conf/common.conf
</VirtualHost>

<VirtualHost 192.168.1.2:443>
  Include conf/common.conf
  (put your ssl specific cofiguration stuff here ...)
</VirtualHost>

You could also specify the common directives within a container instead of within the itself. That's what I do, mostly because I prefer mod_rewrite rules at the directory level instead of at the server level, but it should work equally well for you too.

Related