Learn Labs
Foundations

Configuration & Location Matching

Contexts, inheritance, server selection, and which location wins

Nginx configuration is a tree of contexts containing directives. Most surprises come from three rules: how directives inherit, how a server is chosen, and how a location is chosen.

Contexts

user nginx;main context: process-wide settingsevents { worker_connections 4096; }http {everything HTTPgzip on;inherited by every server and location belowupstream app { ... }named groups of backendsserver {one virtual host: listen + server_namelisten 443 ssl;server_name localhost nginx;location /api/ { ... }what to do for a URI}}

The module's config is config/nginx.conf (main, events, http, upstreams) and config/conf.d/site.conf (the servers), included with include /etc/nginx/conf.d/*.conf;. nginx -T prints the whole thing as Nginx sees it, includes expanded.

Inheritance, and its trap

A directive set in an outer context applies to inner ones unless the inner context sets the same directive. For most directives that's intuitive. For array-like directives, setting one in a location replaces the whole inherited set:

server {
  add_header X-Frame-Options DENY always;           # security headers here...
  add_header X-Content-Type-Options nosniff always;

  location /assets/ {
      add_header Cache-Control "public, immutable";  # ...are all gone in this location
  }
}

The same applies to proxy_set_header. This module puts the security headers in snippets/security-headers.conf and includes it at server level and in every location that adds its own header.

Choosing the server

For each connection, Nginx picks a server block by listen address and port, then by name: the TLS SNI during the handshake, then the HTTP Host header. If nothing matches, the default server for that port answers. Without default_server, that's the first one defined.

In the first version of this config, the site was the default, so it answered for any name:

curl --cacert ca.crt -H 'Host: evil.example' https://localhost:8443/api/whoami
200

A catch-all server now refuses unknown names:

server {listen 443 ssl default_server;server_name _;ssl_reject_handshake on;unknown SNI: handshake fails (TLSV1_UNRECOGNIZED_NAME)return 421;known SNI, unknown Host header: Misdirected Request}

Choosing the location

Within a server, Nginx picks one location per request:

  1. An exact match (location = /api/login) wins immediately.
  2. Otherwise the longest matching prefix is remembered. If it's marked ^~, it wins.
  3. Otherwise regex locations (~, ~*) are tried in file order; the first that matches wins.
  4. If no regex matches, the remembered longest prefix wins.
request= /api/loginexact/api/cached/prefix/api/prefix/assets/prefix~ /\.regex/prefix/api/login✓/api/cached/items✓/api/whoami✓/assets/app.3f9a2c.css✓/.env✓/about✓
/assets/app.3f9a2c.css  200, Cache-Control: public, max-age=31536000, immutable  -> location /assets/
/assets/.secret         404, no Cache-Control                                    -> location ~ /\.  (the regex beat the prefix)
/about                  200 text/html                                            -> location /  (try_files falls back to index.html)

The regex for dotfiles wins over /assets/ because regexes are checked after prefixes and beat them, unless the prefix uses ^~. That's exactly what you want for a security rule, and exactly what surprises people when a broad regex like ~ \.(css|js)$ swallows requests meant for a prefix location.

proxy_pass and the trailing slash

location /lb/round-robin/ { proxy_pass http://app_rr/api/; }GET /lb/round-robin/whoami -> backend sees /api/whoami (matched prefix replaced by /api/)location /api/ { proxy_pass http://app; }GET /api/whoami -> backend sees /api/whoami (no URI in proxy_pass: passed unchanged)

With a URI part in proxy_pass (even just /), the matched location prefix is replaced by it. Without one, the original URI is passed as is.

Lab

  1. Run docker exec nginx nginx -T | less and find every add_header.
  2. Add location ~ \.css$ { return 418; } above the dotfile rule and request /assets/app.3f9a2c.css. Then change /assets/ to ^~ /assets/ and request it again.
  3. Request https://localhost:8443/ with -H 'Host: localhost' and with -H 'Host: other'. Explain both responses.

On this page