Every NGINX feature is a directive in some context; knowing the structure tells you where each line belongs.
NGINX configuration consists of directives. A simple directive is a name, parameters and a semicolon: worker_processes auto;. A block directive contains others in braces and forms a context:
- main: top level; process settings such as
user,worker_processes,error_log. events { }: connection handling, such asworker_connections.http { }: everything about HTTP: MIME types, logging, gzip, and the virtual servers.server { }: one virtual server, defined bylistenandserver_name.location { }: settings for a set of request URIs inside a server.upstream { }: a group of backend servers (insidehttp).stream { }: TCP/UDP proxying, separate from HTTP.
Each directive is only allowed in specific contexts, listed in its documentation.
Settings are inherited downwards: a directive set in http applies to every server and location unless overridden there. The important exception to remember: array-like directives such as add_header and proxy_set_header are inherited only if the inner level defines none of its own. Adding a single add_header in a location silently drops all the headers defined at the server level.
include pulls in other files and accepts globs, which is how per-site configuration files and shared snippets are organized. Comments start with #.
Example
user nginx;
worker_processes auto; # main context
error_log /var/log/nginx/error.log warn;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
add_header X-Frame-Options DENY; # inherited by servers...
server {
listen 80;
location / {
root /usr/share/nginx/html; # ...and by this location
}
}
include /etc/nginx/conf.d/*.conf; # more server blocks
}Remember
- Directives end with ;, blocks create contexts
- main > events / http > server > location
- Inner contexts inherit settings, but add_header-like lists are replaced if redefined
Watch out for
- Adding one add_header in a location and losing all server-level security headers.