Context tree: where each directive belongs
An nginx config is a tree of nested blocks called contexts. Every directive is valid only in specific contexts: putting worker_processes inside http or proxy_pass directly in server makes nginx -t reject the file with directive is not allowed here.
main (top level of nginx.conf: user, worker_processes, error_log, pid)
├── events { worker_connections; … }
├── http {
│ ├── map $source $variable { … } # variable lookup table
│ ├── upstream backend { … } # pool of backend servers
│ └── server { # virtual server (port + domain)
│ ├── listen / server_name / root
│ ├── location / { … } # URI path rules
│ └── location ~* \.png$ { … }
│ }
└── stream { # raw TCP and UDP (non-HTTP)
└── server { listen …; proxy_pass …; }
}
nginx expands every include directive (such as include /etc/nginx/conf.d/*.conf; inside http) in place before parsing the tree. That means files in conf.d/ already sit inside http — write server, upstream, and map directly without wrapping them in another http { … }.
Picking a server block: listen first, then server_name
When a request arrives on a port, nginx picks one server block in two steps:
- Match IP and port on
listen. A specific address (listen 203.0.113.10:80;) beats a wildcard (listen 80;, which means0.0.0.0:80). - Match the
Hostheader againstserver_nameamong the blocks from step 1, following five strict priority tiers:
| Priority | server_name form |
Example | Tie-breaker |
|---|---|---|---|
| 1 | Exact name | app.example.org |
Unique exact match |
| 2 | Leading wildcard | *.example.org |
Longest match (*.api.example.org beats *.example.org) |
| 3 | Trailing wildcard | example.* |
Longest match |
| 4 | Regular expression (~) |
~^api-\d+\.example\.org$ |
First match in config order |
| 5 | Default server | listen 80 default_server; |
Explicit default_server, otherwise the first server on that port |
Notice what tiers 2 and 4 imply: if server_name ~^api-\d+\.example\.org$; appears above server_name *.example.org; on the same port, Host: api-1.example.org still lands in *.example.org because leading wildcards outrank regexes.
server_name _; in a default_server catch-all has no special meaning in nginx’s source code. An underscore is just an invalid hostname that can never match a real Host header; the default_server flag on listen is what makes the block a catch-all.
Picking a location block: the four-step algorithm
Inside the chosen server, a request matches exactly one location. File order does not matter for prefix blocks — modifiers and prefix length decide.
request URI (without ?query string)
- 1. Exact =
location = /Exact character-for-character match stops the search immediately. - 2. Longest prefix
/images/ or ^~ /static/nginx finds the longest matching prefix. If it carries^~, the search stops immediately. - 3. Regex ~ and ~*
location ~* \.png$Evaluated top to bottom in config order. The first match wins and stops the search. - 4. Prefix fallback
winner from step 2If no regex matched, nginx falls back to the longest prefix remembered in step 2.
exactly one location block selected
Summary of all location modifiers:
| Syntax | Match rule | When to use |
|---|---|---|
location = /path |
Exact URI match | Home page = /, /healthz, /robots.txt — instant exit without regex checks |
location ^~ /static/ |
Prefix; skips regexes if longest match | Static asset directories so global regex rules don’t hijack files inside |
location /api/ |
Plain prefix | Most routes; loses to any matching regex |
location ~ \.php$ |
Case-sensitive regex | Forwarding scripts to PHP-FPM or case-sensitive patterns |
location ~* \.(jpg|png)$ |
Case-insensitive regex | Extension rules (matches both .PNG and .png) |
location @fallback |
Named location (unreachable externally) | Internal jumps from try_files or error_page |
Directive inheritance and the add_header trap
nginx directives fall into three categories with different inheritance rules:
- Single-value directives (
root,client_max_body_size,gzip,keepalive_timeout) — inherit fromhttptoservertolocation. Setting one in a child block replaces the inherited value. - Action directives (
return,rewrite,proxy_pass,fastcgi_pass) — never inherit; they apply only in the block where they are written. - Array directives (
add_header,proxy_set_header,fastcgi_param,access_log) — inherit top-down all or nothing. Defining even one directive of the same name in a child block discards the entire parent list for that block.
Rule 3 causes the single most common security bug in nginx configs: server defines Strict-Transport-Security, Content-Security-Policy, and X-Frame-Options, then location /assets/ adds one line — add_header Cache-Control "public, max-age=3600"; — silently wiping every security header from /assets/.
The second add_header quirk is always. Without it, nginx adds the header only to responses with status 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308. Error pages (404, 403, 500) lose the header:
curl -sI -H "Host: app.example.org" http://127.0.0.1/err404
# HTTP/1.1 404 Not Found
# X-Frame-Options: DENY # kept thanks to always; any add_header without always disappeared
proxy_set_header follows the exact same array-inheritance rule: if server sets Host, X-Real-IP, and X-Forwarded-For, and one location adds a single proxy_set_header Upgrade …, all three parent headers stop being sent in that location. Use the same fix: put shared proxy headers in snippets/proxy-headers.conf and include it inside each location.
Request phases: why return runs before allow and try_files
An HTTP request passes through 11 internal phases in nginx. You don’t need all 11 memorized, but knowing the order of the five main phases explains why directives in the same block don’t run in line order:
| Order | Phase | Directives evaluated here |
|---|---|---|
| 1 | rewrite |
set, return, rewrite, if |
| 2 | access |
allow, deny, auth_basic, auth_request, limit_req, limit_conn |
| 3 | try_files |
try_files |
| 4 | content |
static files (root/alias), proxy_pass, fastcgi_pass |
| 5 | log |
access_log |
Two practical consequences follow directly from this table:
- You cannot guard
returnwith IP rules or a password. Inlocation /secret { allow 10.0.0.0/24; deny all; return 200 "secret"; },returnfires duringrewrite— beforeallow/denyrun — so every external client receives"secret". limit_req,allow/deny, andauth_basicshield the backend. They run in theaccessphase ahead ofproxy_passandfastcgi_pass, so blocked or throttled requests never reach your app.
Why if inside location is dangerous and what to use instead
To pick a value based on a header, IP, method, or cookie, replace if chains with a map block inside http:
# /etc/nginx/conf.d/lang-map.conf — inside the http context
map $http_accept_language $lang_pick {
default en;
~*^ru ru;
}
server {
listen 80;
server_name app.example.org;
location = / {
return 302 /$lang_pick/;
}
}
$lang_pick is evaluated only when referenced — only on requests that use it, and once per request. Inside location, you’re left with a plain return and zero if blocks.
How to check
When debugging server_name, location, and headers, skip the browser and its cache — send curl straight to 127.0.0.1 with an explicit Host header:
# Check which server and headers nginx returns for a specific Host and path
curl -sI -H "Host: app.example.org" http://127.0.0.1/assets/app.js
# Test with an extra request header (e.g. Accept-Language for map)
curl -sI -H "Host: app.example.org" -H "Accept-Language: ru-RU,ru;q=0.9" http://127.0.0.1/
If you aren’t sure which of ten location blocks caught a request, temporarily add add_header X-Debug-Loc "images" always; inside the suspect block on a test host, run sudo nginx -t && sudo systemctl reload nginx, and check curl -sI (remove the line afterward).
If it doesn’t work
Strict-Transport-Security, CSP, and X-Frame-Options disappeared on /assets/ even though they are set in server
- Cause
location /assets/defines its ownadd_header Cache-Control. Array-like directives don’t merge with parent blocks: anyadd_headerat a lower level discards everyadd_headerfromserverandhttp.- Fix
- Move shared security headers into
/etc/nginx/snippets/headers.confand addinclude snippets/headers.conf;inside everylocationthat sets its ownadd_header.
Security headers appear on 200 OK pages but vanish on 404, 403, and 500 responses
- Cause
- Without the
alwaysflag,add_headeronly runs on success and redirect codes (200,201,204,206,301,302,303,304,307,308). - Fix
- Append
alwaysto each security header directive:add_header X-Frame-Options "DENY" always;.
Rules in location /images/ don’t apply to .png files inside that directory
- Cause
- A regex block
location ~* \.(png|jpg)$appears elsewhere in the sameserver. Regex locations override plain prefix blocks regardless of file order. - Fix
- Change the prefix block to
location ^~ /images/— the^~modifier stops regex evaluation as soon as that prefix wins by length.
A server block with server_name ~^api-\d+\.example\.org$; misses api-1.example.org — requests hit *.example.org instead
- Cause
- During virtual server selection, a leading wildcard (
*.example.org) always takes precedence over a regular expression, even if the regex block appears higher in the file. - Fix
- Avoid overlapping wildcards and regexes on the same domain: either list the exact name
api-1.example.orgor use the same match type for both rules.
Adding an if check inside location broke try_files or dropped headers
- Cause
- Inside
location,ifcreates a hidden nestedlocationthat drops some parent directives and content handlers. - Fix
- Move branching into a
mapblock insidehttp, and insidelocationlimitifbodies toreturnorrewrite … last.