basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ManualHomelabnginx

    How nginx reads a config: contexts, server, location, and inheritance

    nginx doesn’t execute configs top to bottom like a script — it builds a tree of contexts with strict priority and inheritance rules. Covers how server and location are picked, why one add_header inside a block wipes headers from server, what order request phases run in, and how map replaces if.

    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:

    1. Match IP and port on listen. A specific address (listen 203.0.113.10:80;) beats a wildcard (listen 80;, which means 0.0.0.0:80).
    2. Match the Host header against server_name among 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. 1. Exact =location = /Exact character-for-character match stops the search immediately.
    2. 2. Longest prefix/images/ or ^~ /static/nginx finds the longest matching prefix. If it carries ^~, the search stops immediately.
    3. 3. Regex ~ and ~*location ~* \.png$Evaluated top to bottom in config order. The first match wins and stops the search.
    4. 4. Prefix fallbackwinner 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
    Which location block handles GET /images/logo.png?
    location = /          { return 200 "loc: exact =\n"; }
    location /            { return 200 "loc: prefix /\n"; }
    location /images/     { return 200 "loc: prefix /images/\n"; }
    location ^~ /static/  { return 200 "loc: prefix ^~ /static/\n"; }
    location ~* \.png$    { return 200 "loc: regex png\n"; }
    Which location block handles GET /images/logo.png?
    Answer:
    loc: regex png

    There is no exact = match. The longest prefix is /images/, but it lacks ^~, so nginx moves on to regular expressions. ~* \\.png$ matches first and beats the prefix. To keep /images/logo.png inside /images/, write location ^~ /images/.

    Directive inheritance and the add_header trap

    nginx directives fall into three categories with different inheritance rules:

    1. Single-value directives (root, client_max_body_size, gzip, keepalive_timeout) — inherit from http to server to location. Setting one in a child block replaces the inherited value.
    2. Action directives (return, rewrite, proxy_pass, fastcgi_pass) — never inherit; they apply only in the block where they are written.
    3. 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/.

    Which headers does the browser receive for GET /assets/app.js?
    server {
        listen 80;
        server_name app.example.org;
    
        add_header X-Frame-Options "DENY" always;
    
        location /assets/ {
            add_header Cache-Control "public, max-age=3600";
            return 200 "ok\n";
        }
    }
    Which headers does the browser receive for GET /assets/app.js?
    Answer:
    HTTP/1.1 200 OK · Cache-Control: public, max-age=3600

    add_header is an array directive: declaring add_header Cache-Control inside location /assets/ replaced the entire add_header list inherited from server. To keep shared headers, move them to /etc/nginx/snippets/headers.conf and include that snippet in every location that sets its own add_header.

    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 return with IP rules or a password. In location /secret { allow 10.0.0.0/24; deny all; return 200 "secret"; }, return fires during rewrite — before allow/deny run — so every external client receives "secret".
    • limit_req, allow/deny, and auth_basic shield the backend. They run in the access phase ahead of proxy_pass and fastcgi_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 own add_header Cache-Control. Array-like directives don’t merge with parent blocks: any add_header at a lower level discards every add_header from server and http.
    Fix
    Move shared security headers into /etc/nginx/snippets/headers.conf and add include snippets/headers.conf; inside every location that sets its own add_header.

    Security headers appear on 200 OK pages but vanish on 404, 403, and 500 responses

    Cause
    Without the always flag, add_header only runs on success and redirect codes (200, 201, 204, 206, 301, 302, 303, 304, 307, 308).
    Fix
    Append always to 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 same server. 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.org or use the same match type for both rules.

    Adding an if check inside location broke try_files or dropped headers

    Cause
    Inside location, if creates a hidden nested location that drops some parent directives and content handlers.
    Fix
    Move branching into a map block inside http, and inside location limit if bodies to return or rewrite … last.