Ravindra BagaleCourses & study guides

Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)

7.12 Hosting multiple sites on one server (virtual hosts)

Think of one building with many shops: the building has one address (IP), but each shop has its own name board (domain). Technically, the browser sends the domain in the HTTP Host header, and the web server picks the matching server_name / ServerName block.

One server can host many websites; the web server chooses the site by the Host header (domain name) sent by the browser.

 site1.example.com ─┐                       ┌─► /var/www/site1
                    ├─► 13.233.10.25:80 ────┤
 site2.example.com ─┘   (one IP, one port)  └─► /var/www/site2
# Nginx: one server block per site
server { listen 80; server_name site1.example.com; root /var/www/site1; }
server { listen 80; server_name site2.example.com; root /var/www/site2; }
# Apache: one VirtualHost per site
<VirtualHost *:80>
    ServerName site1.example.com
    DocumentRoot /var/www/site1
</VirtualHost>
<VirtualHost *:80>
    ServerName site2.example.com
    DocumentRoot /var/www/site2
</VirtualHost>

Point both domains' DNS A records to the server's Elastic IP (allocate and attach it as in section 5.5; details in section 14.1). Buying a domain and creating these records step by step is covered in Chapter 9. Without real domains you can test from your laptop by adding a line 13.233.10.25 site1.example.com to your hosts file (/etc/hosts on Linux/Mac, C:\Windows\System32\drivers\etc\hosts on Windows), or with curl -H "Host: site1.example.com" http://13.233.10.25.

Ravindra Bagale's Tip

For projects you show in interviews or put on your resume, spend a little on a domain name and add HTTPS with certbot. A link like https://yourname.dev looks far more professional than http://13.233.x.x. Just remember to attach an Elastic IP first so the DNS record never breaks.