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:
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.
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.
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.
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
masterruns asroot, 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-dataon Debian and Ubuntu,nginxin the official package and Docker image). Withworker_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_connectionsper 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
- server block
listen + server_namePicks the virtual server by IP, port, andHostheader (ordefault_serverif no name matches). - location block
=, ^~, prefix, ~Picks a singlelocationblock by priority rules, rather than top-to-bottom order. - Access checks
allow/deny, limit_reqBlocks denied IPs, checks passwords,auth_request, and rate limits before touching the backend. - Response generation
try_files / proxy_passReads a file from disk, returns a cached hit fromproxy_cache, or proxies to an app or PHP-FPM.
client response (compression, headers, access.log entry)
Where it fits
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 patch1.30.8), receives bug fixes and security patches without behavior surprises. Examples in this track target1.30. It includes standalonehttp2 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 insites-enabled/. - The package ships ready snippets in
/etc/nginx/snippets/(such asfastcgi-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 nosites-available/. - The worker user is
nginx, notwww-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 -tcatches syntax errors before applying anything, andreloadshifts 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),sendfilestatic serving, and TCP/UDPstreamwork 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 (
certbotoracme.shwith areloadhook). - Inheritance and priority traps. An
add_headerinsidelocationsilently drops everyadd_headerfromserver, a regex~overrides a prefixlocation, andifinsidelocationbehaves in surprising ways. - No automatic Docker discovery. If a container behind
proxy_passis recreated with a new IP, nginx keeps hitting the stale address and returns502unless you setresolverand a variable. - No
.htaccess. Any routing or redirect change requiresrootaccess and a service reload. - Active health checks are commercial-only. Open-source nginx takes a node out of
upstreamonly after real requests fail (max_fails).
Where to start
- nginx: how it works, when to pick it, and where to start
- Installing nginx, config layout, and safe reloadsOfficial 1.30 package vs Ubuntu package,
/etc/nginx/layout,nginx -t/-T, zero-downtimereload, and permissions. - How nginx reads a config: contexts, server, location, and inheritanceContexts,
server_nameandlocationselection, theadd_headerinheritance trap, request phases, andmapinstead ofif. - Static 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 viaX-Accel-Redirect. - Reverse proxy in nginx: Node, Python, Go, WebSocket, and SSE streamingProxying to Node/Python/Go, trailing slashes in
proxy_pass, WebSocket viamap, and unbuffered SSE streaming. - HTTPS, 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). - nginx and PHP-FPM: WordPress, Laravel, socket permissions, and fastcgi_cacheWordPress and Laravel:
nginx/www-dataUnix socket permissions, locking down/uploads/,php.inilimits, andfastcgi_cache. - Load balancing and failover in nginx: upstream, keepalive, and a 503 maintenance page
upstreampools, algorithms,keepalive,max_fails/backup, safe retries, and a503maintenance page. - nginx in Docker and in front of containers: unprivileged, templates, and DNS resolver
nginx-unprivileged,/healthz,/etc/nginx/templates/, and dynamic DNS viaresolver 127.0.0.11. - Basic nginx hardening: default_server catch-all, limits, Slowloris, and headers
server_tokens off, adefault_servercatch-all, Slowloris timeouts,limit_except, and a security headers snippet with CSP. - Rate limiting and access control in nginx: limit_req, Cloudflare, auth_request, mTLS, and CrowdSec
limit_req/limit_conn, real client IP behind Cloudflare, locking admin panels (allow,auth_basic,auth_request, mTLS), and CrowdSec. - Tuning nginx: workers, networking, buffers, Gzip, and BrotliWorkers,
worker_rlimit_nofile,sendfile/open_file_cache,gzip/gzip_static, Brotli, and proxy buffering. - nginx caching: proxy_cache, microcaching, stale responses, and spike protection
proxy_cache, microcaching,proxy_cache_lock, servingSTALEwhen the backend is down, and cache bypass. - nginx logs, metrics, and debugging: JSON logs, timings, stub_status, and 499/502/504Reading
access.log, JSON logs with upstream timings,logrotate,stub_status, and tracing499/502/504failures. - TCP, 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). - Bot 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. - Redirects, rewrite, and subpath proxying in nginx: 301/308, map, and proxy_redirect
301/308codes, bulk redirects viamap,returnvsrewrite, and proxying under/app/withproxy_redirect. - CORS and preflight OPTIONS in nginx: origin allowlist, cookies, and API errorsOrigin allowlist via
map,OPTIONSreturning204, cookies withCredentials,Vary: Origin, and preventing duplicate headers. - Large uploads, S3/MinIO, and WebDAV in nginx: zero disk buffering, SigV4, and Immich/NextcloudStreaming uploads without disk buffering, exact
Hostfor SigV4 signatures in MinIO, long timeouts, and WebDAV for Immich/Nextcloud. - Proxying gRPC in nginx: grpc_pass, HTTP/2, long streams, and error statuses
grpc_passandgrpcs://,http2 on;, per-service routing, long-lived streams, and mapping502/504togrpc-status. - Production /etc/nginx/ layout: directory tree, load order, and snippet compatibilityFull
/etc/nginx/tree: thinnginx.conf,00-–08-load order, snippet compatibility, and two sites on top. - nginx cheatsheet: commands, match priorities, variables, and error codesCommands,
server_nameandlocationpriorities, 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
phppackage, 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 skippingreloadafter the edit. - Fix
- Inspect the assembled config with
sudo nginx -T | grep -n server_name. If the site is missing, create theln -slink or place the file in/etc/nginx/conf.d/*.conf, then runsudo 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
Hostmatches noserver_name, nginx hands the request to the block markeddefault_server, or to the firstserverblock 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 uselisten 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(usuallyindex.html) whileautoindexis off, or the nginx worker user (www-dataon Ubuntu,nginxin 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 eitherdirectory index of … is forbiddenorPermission 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_sizeto1m. - Fix
- Raise the limit in the relevant
serverorlocationblock (for exampleclient_max_body_size 32m;) and reload withsudo 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.1inside a sibling container, or the worker user lacks permission on the PHP-FPM Unix socket. - Fix
- Open
/var/log/nginx/error.log:Connection refusedpoints to a stopped service or wrong port;No such file or directoryandPermission deniedpoint to the socket path or permissions.