Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 30 ยท Nginx Configuration

Nginx Configuration Syntax

Learn the Nginx config language: simple and block directives, the main, events, http, server and location contexts, inheritance, include, variables and add_header traps.

Nginx has a small configuration language with only a few rules, and almost every confusing behavior you will meet is a consequence of those rules. A configuration file is a tree: directives are the leaves and the branches, and contexts are the branches that group them. Learn how that tree is written and how values flow from a parent to its children, and the rest of the course (server blocks, locations, proxies, caching) reads like ordinary vocabulary.

The real Nginx cannot run in this page, so real configuration appears in read-only nginx blocks. To make the rules tangible, the runnable stand-ins here are JavaScript programs: a parser that turns configuration text into a tree and a resolver that works out which value each location ends up with, including the inheritance rules that surprise people.

Directives: the two kinds

A configuration is a list of directives. A directive has a name, zero or more arguments separated by spaces, and then either a semicolon or a block in curly braces.

NGINX
worker_processes auto;          # simple directive: name, argument, semicolon

server {                        # block directive: name, braces, children inside
    listen 80;
    server_name example.com www.example.com;
}

A simple directive ends with ;. A block directive has { ... } and contains other directives. A block that can contain directives is called a context. Everything after # on a line is a comment.

Three syntax rules cause most beginner errors:

  • Every simple directive needs its semicolon. A missing ; produces an error that blames the next line (unexpected "}" or directive "x" is not terminated by ";").
  • Quote values with special characters. A value containing spaces, semicolons or braces needs single or double quotes: add_header X-Note "hello world";.
  • Units are part of the value. Sizes use k and m (client_max_body_size 10m;), times use s, m, h, d (expires 7d;). No unit means bytes or seconds depending on the directive.

Contexts

The contexts you use every day form a fixed hierarchy:

NGINX
# main context: the top of the file (worker_processes, user, pid, error_log)
worker_processes auto;

events {                         # connection handling
    worker_connections 1024;
}

http {                           # everything about HTTP
    include mime.types;
    gzip on;

    server {                     # one virtual server (one site)
        listen 80;
        server_name example.com;
        root /var/www/example;

        location / {             # how to handle a URL path
            try_files $uri $uri/ =404;
        }
        location /static/ {
            expires 7d;
        }
    }
}

Each directive is only valid in certain contexts. listen belongs in server, try_files in server or location, worker_processes in the main context. Putting a directive somewhere it does not belong makes nginx -t complain that the directive "is not allowed here". The documentation for each directive lists its allowed contexts, so check there when you see that message.

Other contexts exist (upstream, map, types, if, limit_except, and stream for raw TCP and UDP), and you will meet them in later lessons. The five above are the backbone.

The config tree

main Process-wide settings at the top of the file.
events How connections are accepted.
http Settings shared by every site.
server One virtual server, one site.
1 / 2

Inheritance

Most directives set a value in a context, and the child contexts below inherit it unless they set their own. Set gzip on; once in http and every server and location has it. Set root /var/www/example; in a server and every location in it uses that root, unless a location declares its own.

The rule is simple for single-value directives: the nearest definition wins, looking from the location up to the server and to http.

The exception is the one that catches nearly everyone: directives that can appear multiple times, such as add_header, proxy_set_header, fastcgi_param and error_page. For these, inheritance is all or nothing. If a context contains at least one such directive, it replaces the whole inherited list instead of adding to it.

NGINX
http {
    add_header X-Content-Type-Options nosniff;      # at http level

    server {
        add_header X-Frame-Options DENY;            # replaces the http-level list here

        location /static/ {
            add_header Cache-Control "public";      # replaces the server-level list here
            # Only Cache-Control is sent for /static/ now.
            # X-Frame-Options and X-Content-Type-Options are gone.
        }
    }
}

That is the notorious add_header trap: you add a caching header to one location and quietly lose your security headers there. The fix is to repeat the headers you still want in that location, or to put shared ones in a snippet and include it everywhere. Very recent Nginx releases also add an add_header_inherit directive to opt in to merging, but the repeat-or-include habit works on every version. Also remember that add_header only applies to some status codes unless you add the always flag (add_header X-Frame-Options DENY always;), which matters for error pages. Hardening and Security Headers returns to this.

Include and variables

include inserts other files into the config at that point. It accepts globs, which is how the Debian and Red Hat layouts load sites (see Installing and Finding Your Way Around):

NGINX
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/snippets/security-headers.conf;

The included text behaves exactly as if you had typed it in place, so an included file must be valid in the context where the include appears. A snippet of add_header lines can be included in several location blocks. That is the cure for the repetition problem above.

Variables start with a dollar sign. Nginx provides many built in: $uri (the normalized path), $request_uri (the original, with query string), $args (the query string), $host, $scheme, $remote_addr, $request_method, $status. You can create your own with set or the map directive, and use variables inside strings and many directive arguments:

NGINX
set $upstream_name "blog";
return 301 https://$host$request_uri;
add_header X-Request-Path $uri always;

A word of caution about if: inside location blocks it behaves in surprising ways and is best kept to simple jobs such as return and rewrite. Prefer map, try_files and separate locations. Nginx's own documentation lists the pitfalls, and we avoid if for logic in this course.

Simulation 1: parse the tree

The best way to feel how a config is structured is to build the reader. The script below tokenizes a configuration (words, braces, semicolons, comments and quotes), parses it recursively into directives with children and prints the tree with indentation. It is a stand-in: real Nginx implements far more (context validation, includes, variables), but the shape of the algorithm is the same.

JS Turn nginx config text into a tree

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines show how a missing semicolon produces an error. In the broken config, 80 } is read as the argument 80 followed by a closing brace where a semicolon was expected, so the parser complains at the brace.

Simulation 2: resolve inherited values

Now the interesting part. The script below reuses the same parser and then answers, for every location, two questions: which root does it use (nearest definition wins), and which add_header lines does it send (the whole list of the nearest level that defines any)? Watch which security headers survive in each place.

JS Resolve inheritance for each location

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what happened to /static/: it sends only Cache-Control. The / location sends only X-Frame-Options (the server's list replaced the one from http, so X-Content-Type-Options is not sent there either). The tidy mental model is "each level either inherits the whole list or replaces it". Nothing is ever merged automatically.

Reading and editing a real config

A few habits make Nginx configuration pleasant:

  • Indent consistently (four spaces is conventional) so the tree is visible at a glance.
  • Put each site in its own file and let the main file include them.
  • Run nginx -t after every change, and use nginx -T to print the full merged configuration, which shows exactly what the server sees after all includes.
  • Search the error log when a reload fails: the message names the file and line.
  • Prefer less configuration. Defaults are good, so every line you add is a line to maintain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What ends a simple directive in Nginx?

    Simple directives end with a semicolon. Block directives use curly braces instead. A missing semicolon is the most common syntax error.
  2. 2. A server block sets add_header X-Frame-Options DENY. A location inside it adds add_header Cache-Control public. Which headers does the location send?

    Multi-value directives such as add_header are inherited only if the current level defines none. Defining one in the location replaces the whole inherited list.
  3. 3. root is set in http and again in a server. Which one applies to a location with no root of its own?

    For ordinary single-value directives the nearest enclosing definition wins, so the location uses the server's root.
  4. 4. Which directive lets you reuse the same block of lines in several places?

    include inserts the contents of other files (and glob matches) at that point, as if they had been typed there.

Summary

  • A config is a tree of directives: simple ones end with ;, block ones hold children in { }.
  • The main contexts are main, events, http, server and location; each directive is valid only in certain contexts.
  • Single-value directives inherit downward and the nearest definition wins.
  • Multi-value directives (add_header, proxy_set_header, fastcgi_param, error_page) are inherited all or nothing: defining one replaces the parent's list.
  • include pulls in other files and globs; variables start with $; use if sparingly.
  • Test with nginx -t and inspect the merged result with nginx -T.

Next: Server Blocks and Choosing a Server