Nginx Config by Example: Server Block
Defining virtual hosts with this sample code demonstrating server block configuration for domain handling, listen directive for port binding with default_server parameter, server_name for domain matching, and access/error log configuration.
Code
http {
# Default server configuration
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name example.com www.example.com;
# Access and error logs
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
return 200 "Hello from Nginx!";
}
}
}Explanation
Server blocks in Nginx define virtual hosts, analogous to Apache's virtual host configuration, allowing a single Nginx instance to host multiple websites with distinct settings for each domain or group of domains. Each server block specifies how Nginx handles traffic for specific domain names or IP addresses, enabling multi-site hosting on a single server. Server blocks can be defined in the main nginx.conf file or split across multiple files in the sites-available and sites-enabled directories.
The listen directive specifies the IP address and port on which the server accepts connections, with listen 80 for HTTP and listen 443 ssl for HTTPS. The default_server parameter designates this block as the fallback for requests that don't match any other server_name directive. IPv6 support is enabled with [::]:80 notation. The server_name directive lists domain names this block should respond to, with Nginx selecting blocks by matching the Host header from client requests against these names.
Logging directives access_log and error_log define paths for request logging and error recording respectively. The access_log records every request with details like IP address, timestamp, request method, URI, status code, and user agent. The error_log captures server errors, configuration issues, and application problems. Separate log files per server block enable traffic isolation and easier debugging for specific sites.
Code Breakdown
listen 80 default_server binds to port 80, marks as fallback for unmatched hosts.[::]:80 enables IPv6 support on port 80.server_name defines domains, Nginx matches Host header against these.
