Chapter 8: Configuring Nginx and Apache
8.4 Reading an Apache configuration
Apache uses directives (one per line, no semicolon) and sections in angle brackets:
# /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