Chapter 8: Configuring Nginx and Apache
8.7 Multiple sites with name-based virtual hosts
In section 7.12 we saw the idea. Now let's build it properly: site1.example.com and site2.example.com on one server, plus a catch-all default that answers requests using the raw IP.
for s in site1 site2; do
sudo mkdir -p /var/www/$s
echo "<h1>Welcome to $s</h1>" | sudo tee /var/www/$s/index.html
done
Nginx (AL2023/CentOS: files in conf.d/; Ubuntu: files in sites-available/ plus a symlink for each):
# site1.conf
server {
listen 80;
server_name site1.example.com;
root /var/www/site1;
access_log /var/log/nginx/site1_access.log;
}
# site2.conf
server {
listen 80;
server_name site2.example.com;
root /var/www/site2;
access_log /var/log/nginx/site2_access.log;
}
# 00-default.conf: requests by IP or unknown names
server {
listen 80 default_server;
server_name _;
return 444; # close connection (or: return 301 http://site1.example.com;)
}
# Ubuntu only: enable and disable
sudo ln -s /etc/nginx/sites-available/site1.conf /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/site2.conf /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
Apache:
# 00-default.conf (loads first, so it is the fallback)
<VirtualHost *:80>
ServerName default.invalid
DocumentRoot /var/www/html
</VirtualHost>
# site1.conf
<VirtualHost *:80>
ServerName site1.example.com
DocumentRoot /var/www/site1
ErrorLog /var/log/httpd/site1_error.log
</VirtualHost>
# site2.conf
<VirtualHost *:80>
ServerName site2.example.com
DocumentRoot /var/www/site2
ErrorLog /var/log/httpd/site2_error.log
</VirtualHost>
# Ubuntu Apache: enable sites (log path ${APACHE_LOG_DIR})
sudo a2ensite site1.conf site2.conf
sudo a2dissite 000-default.conf # optional
sudo apache2ctl configtest && sudo service apache2 reload
Test without buying domains:
curl -H "Host: site1.example.com" http://localhost # Welcome to site1
curl -H "Host: site2.example.com" http://localhost # Welcome to site2
curl -I http://localhost # default block answers
From your laptop, add both names to your hosts file pointing to the server's Elastic IP, then open them in the browser. In Chapter 9 we'll replace this trick with real DNS records.