TExcelTAD
Home › Web Servers in Depth: Nginx, HAProxy, Caddy & Traefik › How Nginx Processes a Request

How Nginx Processes a Request

Before tuning Nginx it helps to know what it actually does with a connection. Most "mysterious" Nginx behaviour (a header that disappears, a directive that seems ignored, a reload that doesn't apply) follows from three things: the process model, the configuration contexts and how directives are inherited between them.

Master and workers

Nginx runs one master process (it reads the config, opens the listening sockets, and manages the others) and several worker processes that handle all the connections. Each worker is a single-threaded event loop: it waits on epoll for any of thousands of sockets to become readable or writable and never blocks on one client. That is why Nginx handles tens of thousands of idle keep-alive connections with a few megabytes of memory, and also why a slow, blocking operation inside a worker (a disk read on a slow network filesystem, a Lua script that sleeps) stalls every connection that worker owns.

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
worker_processes 2;
events { worker_connections 512; }
http {
  access_log off;
  server { listen 127.0.0.1:8080; return 200 "worker $pid\n"; }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
ps -o args= -C nginx | sed 's/ -p .*//' | sort
echo "workers: $(pgrep -c -P "$(cat nginx.pid)")"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
nginx: master process nginx
nginx: worker process
nginx: worker process
workers: 2
Directive Context Meaning
worker_processes auto; main one worker per CPU core (the usual setting)
worker_connections 1024; events connections per worker, including connections to backends: a proxied request uses two
worker_rlimit_nofile 8192; main raise the open-files limit for workers (each connection is a file descriptor)
multi_accept on; events accept all pending connections at once instead of one per event

The maximum number of clients is roughly worker_processes × worker_connections, halved when proxying.

Contexts

The configuration is a tree of contexts (blocks). A directive is only valid in some of them, which nginx -t enforces:

nginx
# main context: process-level settings
worker_processes auto;
events { worker_connections 1024; }

http {                                  # everything HTTP
    gzip on;                            # inherited by every server and location below
    upstream app { server 127.0.0.1:9000; }

    server {                            # one virtual host (listen + server_name)
        listen 8080;
        location /api/ {                # a part of the URI space
            proxy_pass http://app;
        }
        location / { root /srv/www; }
    }
}
stream { }                              # raw TCP/UDP proxying (module ngx_stream)

For every request Nginx picks one server (by address, port and Host, see Server Blocks) and then one location (Location Matching Order). Only the directives that apply to that location run. Internally the request then walks through fixed phases: rewrite of the server, location lookup, rewrite of the location, access checks (allow/deny, auth_basic, limit_req), try_files, and finally the content handler (proxy_pass, return, static files), followed by output filters (gzip, add_header) and logging. The order of directives in the file does not change the order of phases: a return placed after deny all; in the file still runs first, because return belongs to the rewrite phase, which comes before access.

Inheritance: the most common trap

Most directives are inherited downwards: set gzip on; in http and every server has it. But array-like directives (add_header, proxy_set_header, error_page, …) follow an all-or-nothing rule: if a block sets the directive at all, it inherits none of the outer values.

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    add_header X-Frame-Options DENY;
    add_header Strict-Transport-Security "max-age=31536000";
    location / { return 200 "home\n"; }
    location /downloads/ {
      add_header Cache-Control "public, max-age=3600";   # replaces BOTH server-level headers
      return 200 "file\n";
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "--- /"; curl -sI 127.0.0.1:8080/ | grep -iE '^(x-frame|strict|cache-control)' | tr -d '\r'
echo "--- /downloads/x"; curl -sI 127.0.0.1:8080/downloads/x | grep -iE '^(x-frame|strict|cache-control)' | tr -d '\r'
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
--- /
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000
--- /downloads/x
Cache-Control: public, max-age=3600

The security headers silently vanished from /downloads/. Two fixes: repeat them in the location (usually through an include snippets/security-headers.conf; file used everywhere), or, from Nginx 1.29.3, add_header_inherit merge;, which is not in the 1.24 used here. The same rule bites proxy_set_header: one proxy_set_header X-Request-Id … in a location drops the Host and X-Forwarded-For lines set at server level.

Also note add_header only applies to responses with status 200, 201, 204, 206, 301, 302, 303, 304, 307 or 308 unless you add the always parameter, so security headers on error pages need always.

Seeing the effective configuration

nginx -T tests the configuration and prints it, with every include expanded and each file labelled. On a server with dozens of snippet files it is the only reliable answer to "what is Nginx actually running?":

bash · try it yourself
mkdir -p snippets
echo 'add_header X-Content-Type-Options nosniff always;' > snippets/headers.conf
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  server { listen 127.0.0.1:8080; include snippets/*.conf; }
}
EOF
nginx -T -p "$PWD" -c nginx.conf -e stderr 2>&1 | grep -E '^# configuration file|nosniff|syntax'
nginx: the configuration file /home/learner/nginx.conf syntax is ok
# configuration file /home/learner/nginx.conf:
# configuration file /home/learner/snippets/headers.conf:
add_header X-Content-Type-Options nosniff always;

Test yourself

A server block sets two add_header lines. A location inside it sets one add_header. Which headers does a response from that location get?

  1. All three
  2. Only the location's one: setting the directive in a block drops all inherited values
  3. Only the server's two
  4. None

Why does a proxied request count twice against worker_connections?

  1. Nginx opens two client sockets
  2. One connection to the client and one to the backend both use a worker connection slot
  3. Because of HTTP/2
  4. It doesn't

What does nginx -T add over nginx -t?

  1. It reloads the server
  2. It also prints the full effective configuration with all includes expanded
  3. It tests TLS
  4. It runs in the foreground