
- A client (browser or CLI such as
curl) sends an HTTP request to Nginx. - Nginx inspects the
Hostheader and selects the matching server block (for example,example1orexample2). - Each server block serves files from its own document root (e.g.
/var/www/example1and/var/www/example2).
- You have a Linux server (Ubuntu/Debian recommended) with Nginx installed.
- You can run commands with
sudo. - Basic familiarity with editing files (e.g.
nanoorvim).
Step 1 — Prepare the environment
- Remove the default enabled site so it does not interfere with this demo:
- Verify no service responds on port 80:
- Copy the default Nginx site to create
example1and then duplicate it forexample2:
- Edit
/etc/nginx/sites-available/example1to serve the first site. A minimal server block looks like:
- Edit
/etc/nginx/sites-available/example2for the second site:
index.html files for each site so we can verify routing:
sites-available into sites-enabled:
curl to simulate requests for each domain by setting the Host header:
Host header does not match any server_name, Nginx will serve the default server for that listen socket — typically the first enabled server block for that address:port (often determined by the alphabetical order of files in /etc/nginx/sites-enabled):
If a request’s
Host header doesn’t match any server_name, Nginx uses the default server for that listen socket. The default is the first server block for that address:port — commonly the first file (alphabetically) in /etc/nginx/sites-enabled/. To explicitly set a default server, use the default_server flag on the listen directive (for example listen 80 default_server;).- To disable a site without deleting its configuration, remove the symlink from
/etc/nginx/sites-enabled/and reload Nginx:
/etc/nginx/sites-available/ for later reuse.
Alternative: combine multiple server blocks in one file (not recommended)
- You can place multiple
server { ... }blocks in a single file and enable that one file with a single symlink. Example combined file:
Keeping each site in its own file under
/etc/nginx/sites-available/ and enabling them with separate symlinks reduces risk. If a single combined file is accidentally edited or removed, multiple sites could be taken down at once.- Create one server block per site and set a unique
server_name. - Point each server block to its own document
root. - Enable sites with symlinks in
/etc/nginx/sites-enabled/. - Always validate config with
sudo nginx -tthen reload withsudo nginx -s reload. - Prefer separate files per site for isolation and safer management.