Nginx Virtual Hosts: Deploying Multiple Websites on a Single Server

This article introduces the Nginx virtual host feature, which allows a single server to host multiple websites, thereby reducing costs. The core is to simulate multiple virtual servers through technology. There are three implementation methods in Nginx: domain name-based (the most common, where different domains correspond to different websites), port-based (distinguished by different ports, suitable for scenarios without additional domains), and IP-based (for servers with multiple IPs, where different IPs correspond to different websites). Before configuration, Nginx needs to be installed, website content prepared (e.g., directories `/var/www/site1` and `/var/www/site2` with homepages), and domain name resolution or test domains (optional) should be ensured. Taking the domain name-based method as an example, the steps are: create the configuration file `/etc/nginx/sites-available/site1.com`, write a `server` block (listening on port 80, matching the domain name, specifying the root directory), configure the second website similarly, create a soft link to `sites-enabled`, test with `nginx -t`, and restart Nginx. For other methods: the port-based method requires specifying a different port (e.g., 8080) in the `server` block; the IP-based method requires the server to bind multiple IPs, with the `listen` directive in the configuration file specifying the IP and port. Common issues include permissions, configuration errors, and domain name resolution, which require checking directory permissions, syntax, and confirming that the domain name points to the server's IP. In summary, Nginx's virtual host feature is a cost-effective solution for hosting multiple websites on a single server, with flexible configuration options based on domain names, ports, or IPs to meet various deployment needs.

Read More