Skip to main content

Complete Analysis of nginx.conf Structure

nginx.conf is the core file that controls all Nginx behavior. Without understanding this file's structure, every configuration change becomes a trial-and-error process. Let's thoroughly master the block hierarchy and directive inheritance principles.


Overall nginx.conf Structure​

Nginx configuration files consist of contexts and directives.

# ============================================================
# Main Context (global settings)
# ============================================================
user nginx; # User to run worker processes
worker_processes auto; # Number of workers (auto = CPU core count)
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

# ============================================================
# Events Context (network event processing)
# ============================================================
events {
worker_connections 1024; # Max concurrent connections per worker
use epoll; # Event processing method (Linux: epoll)
multi_accept on; # Accept multiple connections at once
}

# ============================================================
# HTTP Context (overall HTTP settings)
# ============================================================
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;

include /etc/nginx/conf.d/*.conf;

# --------------------------------------------------------
# Server Context (virtual host)
# --------------------------------------------------------
server {
listen 80;
server_name example.com;
root /var/www/html;

# ----------------------------------------------------
# Location Context (per-URL-path processing)
# ----------------------------------------------------
location / {
index index.html index.htm;
}

location /api/ {
proxy_pass http://127.0.0.1:8080;
}
}
}

Main Context (Global Settings)​

The top-level settings outside the HTTP block that control the Nginx process itself.

user  nginx;               # OS user to run worker processes
worker_processes auto; # auto = number of CPU cores (recommended)
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65535; # Max open file descriptors per worker

Events Context​

Configures network event processing model and connection limits.

events {
worker_connections 1024; # Max connections per worker
# Total max = worker_processes × worker_connections
use epoll; # Linux: epoll (recommended)
multi_accept on; # Accept multiple connections per epoll event
}

HTTP Context​

Contains global HTTP protocol settings. Values set here are inherited by child Server and Location blocks.

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

sendfile on; # Transfer files directly via kernel (reduces syscalls)
tcp_nopush on; # Bundle TCP packets to maximum size
tcp_nodelay on; # Send last packet immediately without delay
keepalive_timeout 65; # Keep-Alive connection duration (seconds)
keepalive_requests 1000;
server_tokens off; # Hide Nginx version from response headers

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1024;

include /etc/nginx/conf.d/*.conf;
}

Server Context (Virtual Host)​

Defines virtual hosts so a single Nginx instance can handle multiple domains and ports.

server {
listen 80;
listen [::]:80; # IPv6
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;

access_log /var/log/nginx/example.access.log main;
error_log /var/log/nginx/example.error.log warn;
}

How Requests Map to Server Blocks​

Nginx uses the Host header to determine which Server block handles a request:

1. Match listen port
2. Exact server_name match (e.g., example.com)
3. Wildcard prefix match (e.g., *.example.com)
4. Wildcard suffix match (e.g., example.*)
5. Regex match (e.g., ~^www\d+\.example\.com$)
6. If no server_name matches, use the block marked default_server
# Default server block — handles requests that don't match any server_name
server {
listen 80 default_server;
server_name _;
return 444; # Close connection without response (blocks unknown domains)
}

Location Context​

Applies different processing to different URL paths within a server block.

Location Matching Types​

server {
# 1. Exact match (=)
location = /favicon.ico {
log_not_found off;
access_log off;
}

# 2. Priority prefix (^~)
# Matches /images/ prefix, skips regex checks
location ^~ /images/ {
root /var/www/static;
expires 30d;
}

# 3. Case-sensitive regex (~)
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}

# 4. Case-insensitive regex (~*)
location ~* \.(jpg|jpeg|png|gif|webp)$ {
expires 7d;
add_header Cache-Control "public";
}

# 5. Plain prefix (no modifier)
location /api/ {
proxy_pass http://backend;
}

# 6. Default fallback
location / {
try_files $uri $uri/ =404;
}
}

Location Matching Priority​

1. Exact match (=)              ← Highest priority
2. Priority prefix (^~)
3. Regex (~, ~*) ← First match in file order
4. Plain prefix (no modifier) ← Longest match wins

Directive Inheritance Rules​

Nginx directives inherit from parent contexts to child contexts.

Main
└── Events
└── HTTP ← Inheritance starts here
└── Server ← Inherits from HTTP, can override
└── Location ← Inherits from Server, can override

Warning: Some directives (like add_header) have different inheritance behavior. If add_header is used anywhere in a child block, alladd_header directives from parent blocks are ignored in that child. Manage headers in one place or use include for shared header files.


Configuration File Separation Strategy (conf.d Pattern)​

In production, split settings into domain/role-specific files rather than one large nginx.conf.

/etc/nginx/
nginx.conf ← Global settings only (includes conf.d/*.conf)
conf.d/
example.com.conf ← example.com virtual host
api.example.com.conf ← API subdomain
upstream.conf ← upstream block definitions
ssl-params.conf ← Common SSL parameters
# After adding new site config, validate and reload
sudo nginx -t && sudo systemctl reload nginx

Summary​

ContextRoleKey Directives
MainProcess-level global settingsuser, worker_processes, error_log
EventsEvent processing modelworker_connections, use epoll
HTTPHTTP-level global settingssendfile, gzip, keepalive_timeout
ServerVirtual host definitionlisten, server_name, root
LocationPer-URL-path processingproxy_pass, try_files, expires