4

I often see examples of VirtualHost configurations where <Directory> blocks are placed outside of the <VirtualHost> stanza like this:

# /etc/httpd/conf.d/example1.conf

<Directory /var/www/html/example1>
    Require all granted
</Directory>

<VirtualHost *:80>
    DocumentRoot "/var/www/html/example1"
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin [email protected]
    ErrorLog "/var/log/httpd/error_log_example1"
    CustomLog "/var/log/httpd/access_log_example1" combined
</VirtualHost>

Isn't the following example with the <Directory> block contained within the <VirtualHost> stanza more semantically correct?

# /etc/httpd/conf.d/example2.conf

<VirtualHost *:80>

    <Directory /var/www/html/example2>
        Require all granted
    </Directory>

    DocumentRoot "/var/www/html/example2"
    ServerName www.example.org
    ServerAlias example.org
    ServerAdmin [email protected]
    ErrorLog "/var/log/httpd/error_log_example2"
    CustomLog "/var/log/httpd/access_log_example2" combined

</VirtualHost>

The second method seems correct to me since the block pertains to the individual VirtualHost and if necessary will override settings in the main httpd.conf.

Edit: The second method would require duplication of the <Directory> block if TLS/SSL is enabled, which isn't very DRY. For this reason the first method seems to be correct.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Alxs
  • 2,170
  • 3
  • 21
  • 31

1 Answers1

3

From the Apache doc on Configuration Sections:

  • <Directory> is processed in the order shortest directory component to longest. For example, <Directory "/var/web/dir"> will be processed before <Directory "/var/web/dir/subdir">.

  • If multiple <Directory> sections apply to the same directory they are processed in the configuration file order.

  • Sections inside <VirtualHost> sections are applied after the corresponding sections outside the virtual host definition. This allows virtual hosts to override the main server configuration.

Both snippets are correct, as is your assumption.

LEI
  • 131
  • 5