As someone who runs Linux servers to host multiple websites, managing virtual hosts with Apache is a day-to-day necessity. Apache’s virtual host functionality allows you to serve multiple sites from a single server, each with their own domain, directory, and configuration. In this article, I’ll walk you through setting up and managing Apache virtual hosts using the command line.
Prerequisites
- A Linux server with Apache installed (
apache2
on Ubuntu/Debian orhttpd
on CentOS/RHEL) - Root or sudo access
- Domain names pointing to your server IP
1. Directory Structure for Your Sites
Begin by creating separate directories for each website you intend to serve.
sudo mkdir -p /var/www/example1.com/public_html
sudo mkdir -p /var/www/example2.com/public_html
Give ownership to the user that manages website files (often www-data
or your user):
sudo chown -R $USER:$USER /var/www/example1.com/public_html
sudo chown -R $USER:$USER /var/www/example2.com/public_html
2. Creating Virtual Host Configuration Files
Copy Apache’s default configuration template to a new file for each site:
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example1.com.conf
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example2.com.conf
Edit each configuration file (using nano
, vim
, or your preferred editor):
sudo nano /etc/apache2/sites-available/example1.com.conf
Set it up similar to below:
<VirtualHost *:80>
ServerName example1.com
ServerAlias www.example1.com
DocumentRoot /var/www/example1.com/public_html
ErrorLog ${APACHE_LOG_DIR}/example1.com_error.log
CustomLog ${APACHE_LOG_DIR}/example1.com_access.log combined
</VirtualHost>
Repeat for example2.com
.
3. Enabling the Virtual Hosts
Enable your new sites and reload Apache:
sudo a2ensite example1.com.conf
sudo a2ensite example2.com.conf
sudo systemctl reload apache2
If you need to disable a site:
sudo a2dissite example1.com.conf
sudo systemctl reload apache2
4. Testing
Make sure your domain points to your server. You can test locally by editing your /etc/hosts
file:
127.0.0.1 example1.com www.example1.com
Then, in a browser or with curl
:
curl http://example1.com
5. Pro Tips
- For HTTPS, use Let’s Encrypt, which can auto-generate SSL certificates and update your virtual hosts.
- Organize config files with comments and consistent naming.
- Use
apachectl configtest
to check for syntax errors before reloading.
Managing virtual hosts through the CLI is efficient and keeps your server configurations reproducible and easy to manage as your fleet of sites grows. Happy hosting!
— Lenny
Leave a Reply