Sub topic 2
Server Blocks: One Nginx, Many Sites
Assume that Nginx is installed and running, you can edit files with sudo, and DNS concepts are familiar. A server block is an Nginx configuration block that describes how to handle requests for one site or group of host names. It is similar to a virtual host in other web servers.
One Nginx process can serve many domains from one IP address. Each site can have a different document root, log file, redirect, or application. Nginx chooses the block for each request instead of starting a separate server process for every site.
A basic pair of sites
The listen directive selects the local address and port where Nginx accepts connections. The server_name directive lists host names that should use the block. The root directive identifies the directory containing static files.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
listen [::]:80;
server_name example.org www.example.org;
root /var/www/example.org/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Both blocks listen on port 80, but their server_name values differ. A request such as http://example.org/ includes Host: example.org. Nginx uses that host name to select the second block and looks for the requested file under /var/www/example.org/html.
The same block can list aliases such as www.example.com. If you want www to redirect instead, give it a separate block with a return directive. Keep each block focused on one site policy.
How the selection works
Nginx first groups server blocks by the address and port from listen. It then compares the request's host name with server_name values in that group. Exact names take priority over wildcard and regular-expression names. If no name matches, Nginx uses the default server for that address and port.
The host name is part of the HTTP request, not the network connection itself. Therefore, several domains can share one IP address and port. The client connects to the same endpoint, then identifies the intended site with the Host header.
Keep site configuration separate
Debian and Ubuntu packages commonly use these directories:
/etc/nginx/sites-available/stores site configuration files./etc/nginx/sites-enabled/contains symbolic links to enabled sites./etc/nginx/nginx.confusually includes files fromsites-enabled.
This layout lets you disable a site by removing its enabled link without deleting its configuration. Other distributions may use /etc/nginx/conf.d/ instead. Check the active include directives before choosing a layout.
Exercise
Why can two server blocks both use listen 80 without causing a port conflict?
Show answer
They belong to the same Nginx listener and are distinguished by the request's Host header and their server_name values.