basforge

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

    RU
    OverviewHomelabnginx

    nginx: how it works, when to pick it, and where to start

    nginx accepts incoming server connections and decides what to do with them: serve a file from disk, forward a request to an app or PHP-FPM, split traffic across several backends, cache a response, or block brute force. One worker per CPU core handles thousands of concurrent clients in a few megabytes of memory, and reloads apply a new config without dropping open connections.

    What problem it solves

    A Node.js, Python, Go, or PHP app can answer HTTP requests on its own, yet one server usually hosts several services while ports 80 and 443 exist only once. On top of that sit shared jobs: TLS termination (HTTP and TLS), response compression, static file serving, rate limiting, and unified logs.

    nginx sits in front of apps or runs as a standalone web server, covering four roles in one process:

    Files from disk

    Static sites and SPAs

    Serves HTML, CSS, scripts, fonts, and media straight from the kernel via sendfile, sets cache headers, and routes single-page apps through try_files.

    HTTP, WebSocket, SSE

    Reverse proxy

    Accepts HTTPS on ports 80 and 443 and forwards requests to apps on 127.0.0.1, inside Docker networks, or on neighbor hosts. Holds long-lived connections and hides service ports from the outside.

    Traffic

    Load balancer and cache

    Splits traffic across multiple app instances (upstream), pulls a failing node out of rotation, and serves hot responses from its disk cache (proxy_cache) without hitting the backend.

    Limits and access

    First line of defense

    Throttles excess traffic (limit_req), drops requests for unknown domains, gates admin panels with passwords, client certificates, or external checks (auth_request), and writes one log stream for CrowdSec.

    You can combine these roles in a single config: the same nginx instance serves static files from disk, forwards /api/ to a Go container, caches public pages for five seconds, and rate-limits /login.

    How it works: master, workers, and the event loop

    nginx’s speed and predictability rest on two choices: splitting processes into master and worker, and running an asynchronous event loop (epoll on Linux).

                             ┌─► worker (core 1) ── epoll: thousands of connections ──► disk / backend
    clients ──► :80 / :443 ──┼─► worker (core 2) ── epoll: thousands of connections ──► disk / backend
                             └─► …
       master process (root): reads config, binds ports, starts and replaces workers
    • master runs as root, but handles no client traffic. It validates the config, binds privileged ports 80 and 443, and manages child processes via signals.
    • Workers run as an unprivileged user (www-data on Debian and Ubuntu, nginx in the official package and Docker image). With worker_processes auto, nginx spawns one worker per available CPU core.
    • Event loop instead of a thread per client. Each worker keeps a table of open sockets (up to worker_connections per worker) and waits for kernel notifications. A slow mobile client occupies one table entry in memory rather than a dedicated process.

    That split gives you zero-downtime reloads (reload). When you edit the config and run nginx -s reload (or systemctl reload nginx), master re-reads the files, starts new workers with the new rules, and tells old workers to stop accepting connections. Old workers finish in-flight responses and exit on their own — active downloads and requests never break.

    Path of an HTTP request through the config

    Once a worker accepts a request, nginx walks it through a fixed pipeline. Config bugs almost always come down to which stage evaluates a directive:

    client · https://app.example.org/api/items

    1. server blocklisten + server_namePicks the virtual server by IP, port, and Host header (or default_server if no name matches).
    2. location block=, ^~, prefix, ~Picks a single location block by priority rules, rather than top-to-bottom order.
    3. Access checksallow/deny, limit_reqBlocks denied IPs, checks passwords, auth_request, and rate limits before touching the backend.
    4. Response generationtry_files / proxy_passReads a file from disk, returns a cached hit from proxy_cache, or proxies to an app or PHP-FPM.

    client response (compression, headers, access.log entry)

    Where it fits

    Common case

    A VPS without a heavy orchestrator

    One or more websites, APIs in Python/Node/Go, PHP-FPM for WordPress or Laravel. The entire config lives as text files in /etc/nginx/, tracked in git and validated with one nginx -t command.

    Inside a Docker static container

    Build a frontend into HTML/JS/CSS (React, Vue, Astro, Hugo) and pack it into nginx:1.30-alpine or nginxinc/nginx-unprivileged. Traefik or another proxy can sit in front while nginx handles only static files, compression, headers, and redirects.

    In front of multiple backends

    Load balance two or three service instances (upstream), fail over to a backup node on error, and serve a 503 maintenance page during deployments.

    High traffic and caching

    A 1–5 second microcache absorbs traffic spikes before a heavy app or database, and proxy_cache_use_stale keeps serving stored pages while the backend restarts.

    Raw TCP and UDP (stream module)

    nginx works beyond HTTP too: a stream block proxies PostgreSQL, Redis, SSH, and UDP services, and routes multiple TLS services on port 443 by SNI without decrypting traffic (ssl_preread).

    Protected file downloads

    With X-Accel-Redirect, the app checks user permissions and returns an empty response with the file path, while nginx streams multi-gigabyte downloads without tying up app workers.

    Release branches, directory layouts, and forks

    Online guides often mix versions and install methods, so directives and paths clash. Here is the current picture.

    Two release branches

    nginx.org maintains two branches side by side:

    • Stable (1.30, even minor) — released in April 2026 (current patch 1.30.8), receives bug fixes and security patches without behavior surprises. Examples in this track target 1.30. It includes standalone http2 on; (since 1.25.1), native HTTP/3 over QUIC (listen 443 quic;), ssl_reject_handshake on; (since 1.19.4), Encrypted ClientHello, and HTTP/2 to backends.
    • Mainline (1.31, odd minor) — gets new features first and branches into the next stable every April. Official docs recommend mainline when you need recent modules and features.

    Two directory layouts

    After installation, disk layout follows one of two patterns:

    Debian / Ubuntu package

    nginx 1.24 on Ubuntu 24.04
    • Site configs live in /etc/nginx/sites-available/ and are enabled via symlinks in sites-enabled/.
    • The package ships ready snippets in /etc/nginx/snippets/ (such as fastcgi-php.conf).
    • The distro version lags behind nginx.org, so newer directives like HTTP/3 are absent in Ubuntu 24.04’s default package.

    nginx.org repo and Docker

    nginx 1.30
    • All server configs live straight in /etc/nginx/conf.d/*.conf — there is no sites-available/.
    • The worker user is nginx, not www-data.
    • Always ships a current stable or mainline build with HTTP/3 and modern TLS defaults.

    Forks and commercial build

    • NGINX Plus — F5’s commercial edition. Open-source nginx lacks active backend health checks (it uses passive checks on live request failures) and an extended JSON metrics API. Most servers cover those with external probes and exporters.
    • Angie — a compatible fork from former nginx developers: reads the same configs and adds built-in ACME certificates plus a live stats API.
    • freenginx — Maxim Dounin’s fork (2024), developed independently from F5 with full config compatibility.

    Alternatives

    The broader history of web servers since 2008 and side-by-side configs for the same task live in Web servers since 2008. Here is a quick comparison against nginx’s closest neighbors.

    Config and use HTTPS certificates Best fit
    nginx 1.30 text server/location blocks, zero-downtime reload external: certbot or acme.sh static files, caching, fine-grained headers, limits, and buffers
    Traefik Docker labels and YAML, auto-discovers containers built-in Let’s Encrypt, wildcard via DNS many changing containers on one host (Traefik)
    Caddy short Caddyfile (3–5 lines per site) built-in ACME and HTTP/3 out of the box fast setup for 1–3 sites without manual TLS wiring
    Apache 2.4 <VirtualHost> and per-directory .htaccess external (certbot) or mod_md legacy projects and shared hosting relying on .htaccess
    HAProxy haproxy.cfg: frontends, backends, ACLs ACME since 3.2 cluster load balancing, active health checks, TCP
    If… Pick
    you need static files, SPA routing, PHP-FPM, server-side caching, or tight header and rate control nginx
    a host runs dozens of Docker containers added and updated constantly Traefik in front (Traefik), with nginx inside static containers
    you have 1–3 sites on a VPS and want HTTPS without setting up certbot Caddy
    you’re migrating a project full of .htaccess rules with no time to rewrite them Apache 2.4 (event + PHP-FPM)
    the main job is HA load balancing with active L4/L7 health checks HAProxy

    Tradeoffs

    What you get

    • Tiny memory footprint. A container or host process with a minimal config uses a few megabytes and holds thousands of concurrent connections on a small VPS.
    • Zero-downtime reloads. nginx -t catches syntax errors before applying anything, and reload shifts traffic to fresh workers while old ones drain active requests.
    • Plain-text configs. Everything lives in git, diffs cleanly, and reproduces on a fresh server with no database or web UI.
    • Rich built-in feature set. Compression, disk caching (proxy_cache, fastcgi_cache), rate limiting (limit_req), sendfile static serving, and TCP/UDP stream work without third-party plugins.
    • Same syntax everywhere. The same directives apply on bare Linux, inside Docker images, and when debugging unfamiliar servers.

    What it costs

    • No built-in auto-HTTPS. You wire Let’s Encrypt issuance and renewal separately (certbot or acme.sh with a reload hook).
    • Inheritance and priority traps. An add_header inside location silently drops every add_header from server, a regex ~ overrides a prefix location, and if inside location behaves in surprising ways.
    • No automatic Docker discovery. If a container behind proxy_pass is recreated with a new IP, nginx keeps hitting the stale address and returns 502 unless you set resolver and a variable.
    • No .htaccess. Any routing or redirect change requires root access and a service reload.
    • Active health checks are commercial-only. Open-source nginx takes a node out of upstream only after real requests fail (max_fails).

    Where to start

    1. Overviewthis pagenginx: how it works, when to pick it, and where to start
    2. ManualInstalling nginx, config layout, and safe reloadsOfficial 1.30 package vs Ubuntu package, /etc/nginx/ layout, nginx -t/-T, zero-downtime reload, and permissions.
    3. ManualHow nginx reads a config: contexts, server, location, and inheritanceContexts, server_name and location selection, the add_header inheritance trap, request phases, and map instead of if.
    4. ConfigStatic sites, SPAs, and file downloads in nginx: line-by-line configsThree ready configs line by line: static sites (Astro/Hugo), SPAs (React/Vue), alias, and protected downloads via X-Accel-Redirect.
    5. ConfigReverse proxy in nginx: Node, Python, Go, WebSocket, and SSE streamingProxying to Node/Python/Go, trailing slashes in proxy_pass, WebSocket via map, and unbuffered SSE streaming.
    6. ManualHTTPS, TLS 1.3, HTTP/2, and HTTP/3 in nginxLet's Encrypt certificates via certbot --webroot, TLS 1.3, HSTS, ssl_reject_handshake, HTTP/2, and HTTP/3 (quic).
    7. Confignginx and PHP-FPM: WordPress, Laravel, socket permissions, and fastcgi_cacheWordPress and Laravel: nginx/www-data Unix socket permissions, locking down /uploads/, php.ini limits, and fastcgi_cache.
    8. ConfigLoad balancing and failover in nginx: upstream, keepalive, and a 503 maintenance pageupstream pools, algorithms, keepalive, max_fails/backup, safe retries, and a 503 maintenance page.
    9. Confignginx in Docker and in front of containers: unprivileged, templates, and DNS resolvernginx-unprivileged, /healthz, /etc/nginx/templates/, and dynamic DNS via resolver 127.0.0.11.
    10. ConfigBasic nginx hardening: default_server catch-all, limits, Slowloris, and headersserver_tokens off, a default_server catch-all, Slowloris timeouts, limit_except, and a security headers snippet with CSP.
    11. ManualRate limiting and access control in nginx: limit_req, Cloudflare, auth_request, mTLS, and CrowdSeclimit_req/limit_conn, real client IP behind Cloudflare, locking admin panels (allow, auth_basic, auth_request, mTLS), and CrowdSec.
    12. ConfigTuning nginx: workers, networking, buffers, Gzip, and BrotliWorkers, worker_rlimit_nofile, sendfile/open_file_cache, gzip/gzip_static, Brotli, and proxy buffering.
    13. Confignginx caching: proxy_cache, microcaching, stale responses, and spike protectionproxy_cache, microcaching, proxy_cache_lock, serving STALE when the backend is down, and cache bypass.
    14. Manualnginx logs, metrics, and debugging: JSON logs, timings, stub_status, and 499/502/504Reading access.log, JSON logs with upstream timings, logrotate, stub_status, and tracing 499/502/504 failures.
    15. ConfigTCP, UDP, and SNI passthrough in nginx: the stream module line by lineL4 proxy for databases and UDP, plus routing TLS by SNI on port 443 without decryption (ssl_preread).
    16. ManualBot protection and WAF in nginx: User-Agent, CrowdSec, and when to add ModSecurity or CorazaBot lists via map, behavioral bans with CrowdSec, and when ModSecurity or Coraza makes sense.
    17. ConfigRedirects, rewrite, and subpath proxying in nginx: 301/308, map, and proxy_redirect301/308 codes, bulk redirects via map, return vs rewrite, and proxying under /app/ with proxy_redirect.
    18. ConfigCORS and preflight OPTIONS in nginx: origin allowlist, cookies, and API errorsOrigin allowlist via map, OPTIONS returning 204, cookies with Credentials, Vary: Origin, and preventing duplicate headers.
    19. ConfigLarge uploads, S3/MinIO, and WebDAV in nginx: zero disk buffering, SigV4, and Immich/NextcloudStreaming uploads without disk buffering, exact Host for SigV4 signatures in MinIO, long timeouts, and WebDAV for Immich/Nextcloud.
    20. ConfigProxying gRPC in nginx: grpc_pass, HTTP/2, long streams, and error statusesgrpc_pass and grpcs://, http2 on;, per-service routing, long-lived streams, and mapping 502/504 to grpc-status.
    21. ConfigProduction /etc/nginx/ layout: directory tree, load order, and snippet compatibilityFull /etc/nginx/ tree: thin nginx.conf, 00-–08- load order, snippet compatibility, and two sites on top.
    22. Cheat sheetnginx cheatsheet: commands, match priorities, variables, and error codesCommands, server_name and location priorities, built-in variables, error codes, and diagnostic one-liners.

    Useful pages to keep alongside:

    • Big-picture view of web servers and config comparisons across Apache, nginx, and Caddy — Web servers since 2008.
    • How TLS handshakes, SNI, HTTP/2, and HTTP/3 work — HTTP and TLS.
    • Opening ports 80 and 443 on the server and closing the rest — The ufw firewall.
    • Comparison with a Docker-first reverse proxy — Traefik.

    If it doesn’t work

    After install nginx refuses to start, and journalctl -u nginx shows bind() to 0.0.0.0:80 failed (98: Address already in use)

    Cause
    Another process holds port 80 — often Apache pulled in by the php package, or a container publishing port 80.
    Fix
    Check who listens on the port: sudo ss -ltnp 'sport = :80'. Disable the extra web server (sudo systemctl disable --now apache2) and start nginx again.

    You edited a site config, yet the browser still shows the old behavior

    Cause
    On Debian and Ubuntu a file in /etc/nginx/sites-available/ isn’t active until symlinked into /etc/nginx/sites-enabled/. The other common cause is skipping reload after the edit.
    Fix
    Inspect the assembled config with sudo nginx -T | grep -n server_name. If the site is missing, create the ln -s link or place the file in /etc/nginx/conf.d/*.conf, then run sudo nginx -t && sudo systemctl reload nginx.

    Opening the server’s IP or an unknown domain serves one of your sites along with its certificate

    Cause
    When Host matches no server_name, nginx hands the request to the block marked default_server, or to the first server block on that port if none is marked.
    Fix
    Add a dedicated catch-all block: on port 80 use listen 80 default_server; return 444;, and on port 443 use listen 443 ssl default_server; ssl_reject_handshake on;.

    A static site returns 403 Forbidden even though the files are in place

    Cause
    The directory has no file matching index (usually index.html) while autoindex is off, or the nginx worker user (www-data on Ubuntu, nginx in the official package) lacks traverse (+x) permission on a parent directory — common under /home/example-user.
    Fix
    Check the exact line in /var/log/nginx/error.log: it will say either directory index of … is forbidden or Permission denied. Keep site roots under /var/www/ with read permissions for the nginx worker user.

    Uploading a file larger than 1 MB fails with 413 Request Entity Too Large

    Cause
    nginx defaults client_max_body_size to 1m.
    Fix
    Raise the limit in the relevant server or location block (for example client_max_body_size 32m;) and reload with sudo nginx -t && sudo systemctl reload nginx.

    nginx returns 502 Bad Gateway instead of the app

    Cause
    nginx couldn’t connect to the backend or the connection dropped: the app is stopped, listens on another port, binds to 127.0.0.1 inside a sibling container, or the worker user lacks permission on the PHP-FPM Unix socket.
    Fix
    Open /var/log/nginx/error.log: Connection refused points to a stopped service or wrong port; No such file or directory and Permission denied point to the socket path or permissions.