π Apache Virtual Hosts
Virtual Hosts let you serve multiple websites from a single server β each with its own domain, root, and logs! Let's level up your Apache configuration. π οΈ
π§ What Are Virtual Hosts?β
Apache Virtual Hosts allow:
- π Hosting multiple domains on one server
- π Per-domain SSL and logs
- π Separate document roots and configs
ποΈ HTTP Virtual Host Example (Port 80)β
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot "/var/www/example"
ErrorLog ${APACHE_LOG_DIR}/example-error.log
CustomLog ${APACHE_LOG_DIR}/example-access.log combined
</VirtualHost>
π Explanation:
ServerName
β Main domainServerAlias
β Extra domains likewww
DocumentRoot
β Web files folder- Logs β Tracks site activity and errors
π HTTPS (SSL) Virtual Host Example (Port 443)β
<VirtualHost *:443>
ServerName secure.example.com
DocumentRoot "/var/www/secure"
SSLEngine on
SSLCertificateFile /etc/ssl/certs/secure.crt
SSLCertificateKeyFile /etc/ssl/private/secure.key
ErrorLog ${APACHE_LOG_DIR}/secure-error.log
CustomLog ${APACHE_LOG_DIR}/secure-access.log combined
</VirtualHost>
β Donβt forget to run:
a2enmod ssl
a2ensite secure.example.com.conf
systemctl reload apache2
π οΈ Setting Up Virtual Hosts on Ubuntu/Debianβ
-
π Create a new vhost config:
sudo nano /etc/apache2/sites-available/example.com.conf
-
β Enable the site:
sudo a2ensite example.com.conf
sudo systemctl reload apache2 -
β To disable:
sudo a2dissite example.com.conf
π Directory Permissions Exampleβ
<Directory /var/www/example>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
π‘ Allows Apache to serve content and respect .htaccess
files.
π Debugging Tipsβ
Run:
apachectl configtest # Check syntax
apachectl -S # List active Virtual Hosts
π Logs:
- π§
/var/log/apache2/error.log
- π
/var/log/apache2/access.log
π‘ Best Practicesβ
-
π§Ό One config per domain (use
sites-available
) -
π Always use SSL in production
-
π― Use
ServerAlias
for subdomains -
π Organize root directories clearly
-
π Use IP-based vhosts if needed:
<VirtualHost 192.168.1.50:80>
π Quick Reference Tableβ
Directive | Description |
---|---|
ServerName | Main domain name |
ServerAlias | Additional domain names |
DocumentRoot | Folder with site content |
ErrorLog | Logs server errors |
CustomLog | Logs site access |
SSLEngine | Enable SSL (HTTPS) |
SSLCertificateFile | SSL public certificate path |
SSLCertificateKeyFile | SSL private key path |
π Thatβs it! Youβre now a Virtual Host pro. Ready for .htaccess.md
or security.md
next? π