Ravindra BagaleCourses & study guides

7. Apache and Nginx: Install and Understand

7.6 Reading an Apache Virtual Host

Apache madhe directives ek line var, semicolon nahi, aani sections angle brackets madhe.

# /etc/httpd/conf.d/mysite.conf   (Ubuntu: /etc/apache2/sites-available/mysite.conf)
<VirtualHost *:80>
    ServerName  example.com
    ServerAlias www.example.com
    ServerAdmin webmaster@example.com

    DocumentRoot /var/www/mysite
    DirectoryIndex index.html index.php

    <Directory /var/www/mysite>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorDocument 404 /404.html
    ErrorLog  /var/log/httpd/mysite_error.log
    CustomLog /var/log/httpd/mysite_access.log combined
</VirtualHost>

(On Ubuntu use ${APACHE_LOG_DIR}/mysite_error.log, which points to /var/log/apache2/.)

Directive What it does
<VirtualHost *:80> A site listening on port 80 of all IPs
ServerName / ServerAlias Main host name / extra names for this site
DocumentRoot Folder that URL paths map to
DirectoryIndex File served for a folder request
<Directory path> Rules for a folder on disk
Options -Indexes Disable automatic folder listing
AllowOverride All Allow .htaccess files (needed by WordPress permalinks)
Require all granted Allow everyone to access this folder (Apache 2.4 syntax)
ErrorLog / CustomLog Per-site log files
Listen Ports Apache binds to (in httpd.conf or ports.conf)
ServerTokens Prod + ServerSignature Off Hide version details

No inline comments in Apache

Require all granted # allow all is an error in Apache. Comments must be on their own line starting with #.

How Apache chooses the virtual host

For a given IP:port, Apache compares the Host header with every ServerName/ServerAlias. If none matches, the first virtual host loaded for that port answers, and files load in alphabetical order. That's why Ubuntu's default site is called 000-default.conf: it sorts first. sudo apachectl -S (Ubuntu: sudo apache2ctl -S) prints this list, showing which vhost is the default:

*:80   is a NameVirtualHost
       default server example.com (/etc/httpd/conf.d/mysite.conf:1)
       port 80 namevhost example.com (/etc/httpd/conf.d/mysite.conf:1)
               alias www.example.com

Why this matters for security

Options -Indexes stops Apache from listing folder contents – without it, a folder with no index.html shows every file, including backups and configs. AllowOverride All lets .htaccess files change security settings, so only allow it where the application needs it.

Ravindra Bagale's Tip

In Apache, if you write a comment at the end of a line (Require all granted # allow), the configtest fails – many students get confused. In Apache, a comment always goes on its own line, starting with #.

Practice task

Run sudo apachectl -S (Ubuntu: sudo apache2ctl -S) and write down which virtual host is the default for port 80.