Configuration structure: directives and contexts

NGINX · Essentials · 10 min

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 as worker_connections.
  • http { }: everything about HTTP: MIME types, logging, gzip, and the virtual servers.
  • server { }: one virtual server, defined by listen and server_name.
  • location { }: settings for a set of request URIs inside a server.
  • upstream { }: a group of backend servers (inside http).
  • 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.

Check yourself

  1. The server block sets two add_header lines; a location inside it sets one different add_header. Which headers does that location send?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: nginx.org/en/docs/beginners_guide.html#conf_structure