basforge

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

    RU
    ConfigHomelabnginx

    Production /etc/nginx/ layout: directory tree, load order, and snippet compatibility

    How to combine every nginx snippet and config on one server without conflicts: a thin nginx.conf, 00-–08- load order in conf.d/, three shared snippets in snippets/, a dedicated stream.d/ for L4 traffic, and two production sites on top.

    /etc/nginx/ tree and 00-–08- load order

    Once a server hosts more than one site, assemble the configs from individual guides into one clean tree with clear boundaries: global defaults in 00-–08-, reusable snippets in snippets/, one file per domain, and L4 rules in stream.d/.

    /etc/nginx/
    ├── nginx.conf                    # thin skeleton: workers, events, http, stream
    ├── mime.types                    # package MIME types (leave untouched)
    ├── snippets/                     # NOT auto-loaded — explicit include only
    │   ├── tls.conf                  # TLS 1.2/1.3 and shared session cache
    │   ├── headers.conf              # X-Content-Type-Options, X-Frame-Options, CSP
    │   └── proxy-headers.conf        # proxy_http_version 1.1, Host, X-Real-IP, X-Forwarded-*
    ├── conf.d/                       # included inside http {} in alphabetical order (*.conf)
    │   ├── 00-default.conf           # default_server catch-alls on :80 (444) and :443 (reject)
    │   ├── 01-hardening.conf         # server_tokens off, timeouts, body and header limits
    │   ├── 02-maps.conf              # shared maps: WebSocket ($connection_upgrade), CORS, redirects
    │   ├── 02-realip.conf            # only when behind Cloudflare or another proxy
    │   ├── 03-ratelimit.conf         # geo/map exemptions and limit_req_zone / limit_conn_zone
    │   ├── 04-performance.conf       # sendfile, tcp_nopush, tcp_nodelay, open_file_cache
    │   ├── 05-compression.conf       # gzip, gzip_static, gzip_types
    │   ├── 06-logging.conf           # log_format json_timing, map $loggable, access_log
    │   ├── 07-bots.conf              # map $bad_bot, $bots_welcome, $deny_bot
    │   ├── 08-status.conf            # stub_status on 127.0.0.1:8081 only
    │   ├── app.example.org.conf      # reverse proxy + WebSocket
    │   ├── example.org.conf          # static site / SPA
    │   └── old.example.org.conf.disabled   # disabled site — skipped by *.conf
    └── stream.d/                     # included inside stream {} (outside http!)
        └── postgres-sni.conf         # when using TCP/UDP or SNI routing

    On Linux, include /etc/nginx/conf.d/*.conf; reads files alphabetically, so the 00-–08- numeric prefixes solve three things at once:

    • log_format must load before any access_log that references it: 06-logging.conf always comes before domain files a…z.
    • 00-default.conf always loads first on ports 80 and 443 — even if default_server is accidentally removed somewhere, the catch-all stays the first block rather than a live site.
    • Global plumbing stays separate from sites: in ls /etc/nginx/conf.d/ and nginx -T, shared rules sit neatly at the top and domains follow in alphabetical order.
    File in conf.d/ What it sets Line-by-line guide
    00-default.conf Drops unknown Host (444) and unknown SNI (ssl_reject_handshake) Hardening, HTTPS & HTTP/3
    01-hardening.conf server_tokens off, Slowloris timeouts, body and header limits Hardening
    02-maps.conf, 02-realip.conf map tables (WebSocket, CORS, redirects) and trusted proxy subnets Reverse proxy, CORS & preflight, Limits & access
    03-ratelimit.conf limit_req_zone and limit_conn_zone, 429 status Limits & access
    04-performance.conf sendfile, tcp_nopush, tcp_nodelay, open_file_cache Tuning & compression
    05-compression.conf gzip, gzip_static, text MIME types Tuning & compression
    06-logging.conf log_format json_timing, /healthz filter, buffered access_log Logs & debugging
    07-bots.conf Bad-bot filter via map while keeping /robots.txt open Bots & WAF
    08-status.conf Local /nginx_status on 127.0.0.1:8081 Logs & debugging

    Skip any file your server doesn’t need (for example 02-realip.conf without Cloudflare or stream.d/ without L4 proxying) — the other layers have no hard dependency on it.

    Thin /etc/nginx/nginx.conf with no duplicates

    The most common failure when assembling this tree is leaving the stock /etc/nginx/nginx.conf untouched. The default nginx.org file already puts sendfile on;, keepalive_timeout 65;, log_format main, and access_log inside http {}. Drop 01-hardening.conf, 04-performance.conf, and 06-logging.conf on top, and nginx -t fails immediately with directive is duplicate — or two access_log directives write every request twice.

    Strip nginx.conf down to a thin skeleton holding only process settings, the descriptor limit, mime.types, and two include lines.

    /etc/nginx/nginx.conf
    user nginx;
    worker_processes auto;
    worker_rlimit_nofile 16384;
    
    error_log /var/log/nginx/error.log warn;
    pid       /run/nginx.pid;
    
    events {
        worker_connections 4096;
    }

    The nginx.org package runs workers as nginx (Ubuntu’s distro package uses www-data, Install & layout). worker_rlimit_nofile keeps the open-socket ceiling well above worker_connections (Tuning & compression).

    default:worker_processes 1worker_connections 512

    http {
        include      /etc/nginx/mime.types;
        default_type application/octet-stream;
    
        include /etc/nginx/conf.d/*.conf;
    }
    Key part

    Inside http {} there is intentionally no sendfile, keepalive_timeout, gzip, or access_log: each directive lives in exactly one file under conf.d/01-–06-. Every file in conf.d/ is already inside http {}.

    stream {
        include /etc/nginx/stream.d/*.conf;
    }

    Top-level stream {} block for TCP/UDP and SNI routing without decryption (TCP/UDP stream). An empty /etc/nginx/stream.d/ directory causes no error with *.conf; drop the block entirely if you don’t use stream.

    Compatibility rules for the three files in /etc/nginx/snippets/

    Unlike conf.d/, you create /etc/nginx/snippets/ manually (sudo mkdir -p /etc/nginx/snippets), and nginx never auto-loads it — each snippet applies only where included. Keep three compatibility rules in mind when combining them on one host:

    • snippets/tls.conf (HTTPS & HTTP/3) — include in every HTTPS server block. Having ssl_session_cache shared:SSL:10m; inside the snippet works safely across dozens of server blocks because they all share the same SSL zone without conflict.
    • snippets/headers.conf (Hardening) — include in server {} and repeat in every location that defines its own add_header (such as /assets/ caching or CORS headers in CORS & preflight). Otherwise list-based inheritance drops all security headers on that route (add_header inheritance).
    • snippets/proxy-headers.conf (Reverse proxy) — include only inside the proxied location, right before proxy_set_header Connection ...;. Never place it at the server {} level: a single proxy_set_header Connection ""; inside location would wipe Host, X-Real-IP, and X-Forwarded-* inherited from server. For S3/MinIO, where SigV4 signatures require the original Host $http_host, write the headers explicitly instead of using this snippet (Large uploads & S3).

    Two production sites on top of the layout

    Below are the 00-default.conf catch-all (after deleting the stock /etc/nginx/conf.d/default.conf) and two sites layered on top of the tree: static example.org and proxied app.example.org with WebSocket and keepalive.

    /etc/nginx/conf.d/00-default.conf, example.org.conf, and app.example.org.conf
    # /etc/nginx/conf.d/00-default.conf
    server {
        listen 80 default_server;
        server_name _;
        return 444;
    }
    
    server {
        listen 443 ssl default_server;
        server_name _;
        ssl_reject_handshake on;
    }

    Combined catch-all on both ports in /etc/nginx/conf.d/00-default.conf: drops direct-IP and unknown-domain traffic without exposing any live site’s certificate. Remove the stock /etc/nginx/conf.d/default.conf first.

    # /etc/nginx/conf.d/example.org.conf
    server {
        listen 80;
        server_name example.org www.example.org;
    
        location ^~ /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
        location / {
            return 301 https://example.org$request_uri;
        }
    }
    
    server {
        listen 443 ssl;
        http2 on;
        server_name example.org;
    
        ssl_certificate     /etc/letsencrypt/live/example.org/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem;
        include snippets/tls.conf;
        include snippets/headers.conf;
    
        root  /var/www/example.org;
        index index.html;
    
        if ($deny_bot) {
            return 403;
        }
    
        limit_req  zone=site_limit burst=20 nodelay;
        limit_conn per_ip_conn 20;
    
        location = /healthz {
            return 200 "ok\n";
        }
    
        location /assets/ {
            include snippets/headers.conf;
            add_header Cache-Control "public, max-age=31536000, immutable" always;
        }
    
        location ~ /\.(?!well-known) {
            deny all;
        }
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    Key part

    Static site /etc/nginx/conf.d/example.org.conf: HTTP redirect with a Let's Encrypt exception, TLS 1.2/1.3 and HTTP/2, shared security headers, bot filtering from 07-bots.conf, and rate limits from 03-ratelimit.conf. /assets/ re-includes headers.conf so Cache-Control doesn’t wipe CSP and the rest.

    # /etc/nginx/conf.d/app.example.org.conf
    upstream app_backend {
        server 127.0.0.1:3000;
        keepalive 32;
    }
    
    server {
        listen 443 ssl;
        http2 on;
        server_name app.example.org;
    
        ssl_certificate     /etc/letsencrypt/live/app.example.org/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/app.example.org/privkey.pem;
        include snippets/tls.conf;
        include snippets/headers.conf;
    
        client_max_body_size 16m;
    
        if ($deny_bot) {
            return 403;
        }
    
        location / {
            include snippets/proxy-headers.conf;
            proxy_set_header Upgrade    $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_pass http://app_backend;
        }
    }
    Key part

    Reverse proxy /etc/nginx/conf.d/app.example.org.conf: upstream pool with keepalive and a local client_max_body_size 16m overriding the global 1m from 01-hardening.conf. proxy-headers.conf sits inside location / alongside $connection_upgrade from 02-maps.conf — one block handles both keepalive (variable stays empty on plain HTTP) and WebSocket.

    How to check

    1. Check syntax, duplicate directives, and exact file load order (confirm default.conf is gone and 00-–08- appear before site configs):
      sudo nginx -t
      sudo nginx -T 2>/dev/null | grep '^# configuration file'
      sudo systemctl reload nginx
    2. Test the default_server catch-all on both ports:
      curl -sS -H "Host: unknown.invalid" http://127.0.0.1/
      # curl: (52) Empty reply from server
      curl -sS --resolve unknown.invalid:443:127.0.0.1 https://unknown.invalid/
      # OpenSSL: ... tlsv1 unrecognized name
    3. Confirm /assets/ returns gzip, Cache-Control, hidden version (server: nginx), and every security header from snippets/headers.conf:
      curl -sSI -H "Accept-Encoding: gzip" https://example.org/assets/app.js \
        | grep -iE '^(HTTP/|server:|content-encoding:|cache-control:|x-content-type-options:|content-security-policy:)'
    4. Test the bot filter (403 on /, 200 on /robots.txt), the JSON log without /healthz noise, and local stub_status:
      curl -s -o /dev/null -w "%{http_code}\n" -A "GPTBot/1.0" https://example.org/          # 403
      curl -s -o /dev/null -w "%{http_code}\n" -A "GPTBot/1.0" https://example.org/robots.txt # 200
      curl -s http://127.0.0.1:8081/nginx_status
      sudo tail -n 5 /var/log/nginx/access.log

    If it doesn’t work

    nginx -t fails with "keepalive_timeout" directive is duplicate or "sendfile" directive is duplicate

    Cause
    The stock /etc/nginx/nginx.conf from nginx.org already defines sendfile on; and keepalive_timeout 65;, which collide with conf.d/01-hardening.conf or 04-performance.conf at the same http level.
    Fix
    Remove duplicate directives from http {} in nginx.conf and keep each global setting in exactly one file.

    nginx -t fails with unknown log format "json_timing"

    Cause
    An access_log directive referencing that format appeared before log_format json_timing was declared — for instance, left inside nginx.conf above include /etc/nginx/conf.d/*.conf;.
    Fix
    Keep log_format and the default access_log together in conf.d/06-logging.conf, which loads before any domain config a…z.

    nginx -t fails with a duplicate default server for 0.0.0.0:80 or :443

    Cause
    The stock /etc/nginx/conf.d/default.conf is still present alongside 00-default.conf, or a second site sets default_server on the same port.
    Fix
    Delete the stock default.conf and keep a single default_server per port (80 and 443) inside 00-default.conf (default_server catch-all).

    nginx -t fails with "stream" directive is not allowed here

    Cause
    A TCP/UDP proxy config containing stream { ... } was placed in /etc/nginx/conf.d/, which is included inside http {}.
    Fix
    Move L4 configs into /etc/nginx/stream.d/*.conf and include them from a top-level stream {} block in nginx.conf (TCP/UDP stream).

    Security headers from snippets/headers.conf vanished on /assets/, or a proxied backend stopped receiving Host and X-Real-IP

    Cause
    add_header and proxy_set_header inherit as whole lists: a single directive of that type inside a location drops every directive of the same type from server (add_header inheritance).
    Fix
    Repeat include snippets/headers.conf; inside every location that sets its own add_header, and always place include snippets/proxy-headers.conf; inside the proxied location next to proxy_set_header Connection.

    You added a new site file in conf.d/ and reloaded nginx, yet the site didn’t load

    Cause
    include /etc/nginx/conf.d/*.conf; loads only files ending in .conf (Ubuntu’s distro package also requires a symlink in sites-enabled/).
    Fix
    List the loaded config files with sudo nginx -T 2>/dev/null | grep '^# configuration file' and check the filename extension.