Host header.
By consolidating sites on one machine, you reduce infrastructure costs and simplify management—just one SSH session to maintain all your domains.
How Nginx Virtual Servers Work
When a request arrives, Nginx inspects theHost header (e.g., example.com, mail.example.com) and matches it against configured server blocks:
- Nginx listens on a port (80 or 443 by default).
- It checks the
Hostheader. - It routes the request to the server block with the matching
server_name.
Configuring a Basic Virtual Host
Here’s a minimal example forexample.com:
listen 80;
Binds this block to port 80 (HTTP).server_name
Lists domains and subdomains handled here.root
Points to the document root where your site files live.index
Specifies the default file to serve.location /
Tries to serve the requested URI or returns404if not found.
Binding to an IP Address
You can serve content directly from an IP address instead of a domain:Serving on a Non-Standard Port
If your application runs on a different port (e.g., Jenkins on 8080), you can expose it:http://wiki.example.com:8080.
For production, it’s best to configure a reverse proxy on ports 80/443 and forward traffic internally to port 8080. This avoids requiring users to specify
:8080 in the URL.Managing Multiple Server Blocks
You can place several server blocks in one file, but for maintainability, isolate each site into its own configuration:Keep each site’s configuration in its own file (e.g.,
/etc/nginx/sites-available/honda.cars.com and symlink to /etc/nginx/sites-enabled/). A typo in one file won’t take down all your sites when you reload Nginx.Quick Reference: Nginx Directives
| Directive | Purpose | Example |
|---|---|---|
| listen | Port for incoming connections | listen 80; |
| server_name | Domain(s) served by this block | server_name example.com www.example.com; |
| root | Path to website files | root /var/www/example.com/html; |
| index | Default file to serve | index index.html; |
| location / | URI handling and fallback rules | try_files $uri $uri/ =404; |