Nginx Is Not Just a Web Server: Six Roles, One Tool
· nginx, reverse-proxy, load-balancing, caching, devops
The short video above is right about the headline: Nginx is not just a web server. One process tree can serve files, terminate TLS, cache responses, load-balance HTTP, proxy raw TCP and UDP, and front mail protocols. This study version keeps that six-role map, then adds working configuration, official module names, and the places where a two-minute caption is slightly loose.
Syntax below follows the nginx.org documentation. Always run nginx -t before nginx -s reload (or systemctl reload nginx). For the stack around this, see the OSI model guide. A common Kubernetes ingress controller is Nginx in roles 2–4; see the Kubernetes concepts guide. On AWS the same split shows up as CloudFront, ALB, and security groups in the AWS interview guide.
How the six roles share one binary
A default nginx.conf has an http { } context. That is enough for roles 1–4 (web server, reverse proxy, cache, HTTP load balancer). Roles 5 and 6 live in separate top-level contexts, stream { } and mail { }, provided by ngx_stream_core_module and ngx_mail_core_module.
Those modules are not always present. Official configure flags are --with-stream and --with-mail (and often --with-stream_ssl_module, --with-mail_ssl_module). Many Linux packages ship them as dynamic modules you must load:
load_module modules/ngx_stream_module.so;
load_module modules/ngx_mail_module.so;
If nginx -t complains that stream or mail is unknown, the module is missing, not "Nginx cannot do that job." On Debian/Ubuntu the stream package is often libnginx-mod-stream; names vary by distro. Check nginx -V for the compile-time arguments.
Workers are event-driven, as the video says: one worker can hold many connections. The practical cap is still worker_processes (often auto) times worker_connections, plus file descriptors and memory.
1. Web server: files from disk
In this role Nginx maps a URL to a file under root (or alias) and returns it. HTML, CSS, images, and video files are just bytes with a Content-Type. sendfile, tcp_nopush, and gzip make that path efficient.
server {
listen 80;
listen [::]:80;
server_name www.example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(css|js|mjs|png|jpg|jpeg|webp|svg|woff2|mp4)$ {
expires 7d;
add_header Cache-Control "public, immutable";
access_log off;
}
}
try_files serves the file if it exists, otherwise 404. For a single-page app, end with /index.html instead of =404.
This role is only as safe as the filesystem mapping. Do not point root at secrets, and watch alias trailing slashes — a missing slash can expose the parent directory.
2. Reverse proxy and TLS termination
A reverse proxy accepts the client connection and opens a second connection to an upstream app. Clients talk only to Nginx. That is what the video means by hiding servers. It does not magically hide the origin if you leak it in headers, DNS, or error pages, and the app still needs its own network controls.
TLS termination means Nginx does the HTTPS handshake and forwards HTTP (or HTTP/2/gRPC, if configured) inland:
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name www.example.com;
ssl_certificate /etc/nginx/tls/fullchain.pem;
ssl_certificate_key /etc/nginx/tls/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
}
}
Always set Host and the X-Forwarded-* headers, or the app will generate wrong URLs and logs. A trailing slash on proxy_pass changes path rewriting — proxy_pass http://backend/ is not the same as proxy_pass http://backend. Test both. For WebSockets, add the Upgrade and Connection headers the official proxy docs describe.
Redirect HTTP to HTTPS with return 301 https://$host$request_uri; on a listen 80 server.
3. Content cache
Nginx can store upstream responses on disk with proxy_cache_path / proxy_cache. The next request can be served from that cache if the response is cacheable.
http {
proxy_cache_path /var/cache/nginx/app
levels=1:2
keys_zone=appcache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
listen 443 ssl;
server_name www.example.com;
# tls as above
location / {
proxy_pass http://backend;
proxy_cache appcache;
proxy_cache_valid 200 301 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
}
}
}
$upstream_cache_status reports HIT, MISS, EXPIRED, BYPASS, STALE, and similar values — use it when you debug.
Nuance on "answered instantly": a cache hit is fast, but Nginx will not cache everything.
Cache-Control: privateorno-store,Set-Cookie, and authorization headers often prevent caching unless you deliberately override them withproxy_ignore_headers— which is dangerous for personalized pages.inactiveevicts entries that nobody has touched, even if they are still "fresh." The first request is a MISS and still hits the backend. "Instantly" is a HIT on a cacheable object, not a property of every URL.
4. Load balancer
An upstream group is the official way to spread HTTP requests. If you specify no method, Nginx uses weighted round robin — "round robin by default" in the video is right, with the official qualifier that weights change how often a server is chosen (server 10.0.1.11:8080 weight=3;).
upstream backend {
# default: weighted round robin
# least_conn;
# ip_hash;
# hash $request_uri consistent;
server 10.0.1.11:8080 weight=3 max_fails=2 fail_timeout=10s;
server 10.0.1.12:8080 max_fails=2 fail_timeout=10s;
server 10.0.1.13:8080 backup;
}
server {
listen 443 ssl;
server_name www.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_next_upstream error timeout http_502 http_503;
}
}
Official open-source methods include least_conn (fewest active connections, then weighted round robin among ties) and ip_hash (sticky sessions from the first three octets of an IPv4 address, or the whole IPv6 address). The generic hash directive can key on a variable, optionally consistent.
Nuance on "if one server dies, Nginx stops sending it traffic": open-source Nginx uses passive checks. After
max_failsunsuccessful attempts withinfail_timeout(defaults: 1 failure, 10 seconds), the server is skipped for anotherfail_timeout. An unsuccessful attempt is defined byproxy_next_upstreamand friends. There is no background probe unless you add something else. Active health checks (health_check) are an NGINX Plus feature.least_time(pick the server with the lowest average response time) was Plus-only until Nginx 1.31.0; official docs say that from 1.31.0 it is no longer subscription-only. In an interview, mention both: Plus/active checks, and the 1.31 change forleast_time.
Mark a server down when using ip_hash if you must take it out without reshuffling everyone else, as the official ip_hash example shows. A backup server is used only when the primaries are unavailable.
5. TCP/UDP proxy (the stream module)
HTTP proxy_pass only understands HTTP. Database connections, raw TLS passthrough, and DNS need the stream module. That configuration is a sibling of http { }, not a location inside it.
# at the top level, after load_module if needed
stream {
upstream pg_up {
least_conn;
server 10.0.3.11:5432 max_fails=2 fail_timeout=10s;
server 10.0.3.12:5432 max_fails=2 fail_timeout=10s;
}
server {
listen 5432;
proxy_pass pg_up;
proxy_timeout 10m;
proxy_connect_timeout 5s;
}
upstream dns_up {
server 10.0.2.53:53;
server 10.0.2.54:53;
}
server {
listen 53;
listen 53 udp;
proxy_pass dns_up;
proxy_responses 1; # typical single UDP DNS reply
proxy_timeout 10s;
}
}
listen 53 udp is the official pattern for UDP. DNS is a good example, but remember that DNS can use TCP as well (zone transfers, large answers), which is why the snippet listens on both. Stream can also do TLS passthrough or TLS termination with the stream SSL module. This is L4 proxying: Nginx does not parse SQL or DNS semantics beyond what you configure (timeouts, proxy_responses for UDP).
6. Mail proxy: IMAP, POP3, SMTP
The mail module lets Nginx accept IMAP, POP3, and SMTP and proxy them to a backend chosen by an authentication HTTP server. That auth_http endpoint is required. Nginx does not store mail. It is a protocol-aware proxy: after the auth service returns Auth-Status: OK and a backend address in the response headers, Nginx connects there and forwards the session.
mail {
server_name mail.example.com;
auth_http http://127.0.0.1:9000/mail-auth;
auth_http_header X-Auth-Key "change-me";
proxy on;
proxy_pass_error_message on;
server { listen 143; protocol imap; }
server { listen 110; protocol pop3; }
server { listen 25; protocol smtp; }
# typical secure listeners; certificates as in the http servers
# server { listen 993 ssl; protocol imap; }
}
The auth protocol is header-based; the response body is ignored. If you omit auth_http, mail proxying will not work. TLS for mail is configured with the mail SSL module, separately from your http server blocks. This is why many teams still terminate mail on a dedicated MTA and use Nginx only for HTTP — but the capability is real, and it is one of the six roles in the video.
Test, reload, and a few hardening defaults
sudo nginx -t
sudo nginx -s reload
# or: sudo systemctl reload nginx
reload starts new workers and drains the old ones. restart drops connections. Use reload in production.
Harden the HTTP edge: server_tokens off;, modern ssl_protocols, limit_req_zone / limit_conn, and headers such as Content-Security-Policy and X-Content-Type-Options on HTML locations. Do not cache authenticated responses. Do not proxy_pass to an internal network you did not mean to expose. Workers should run as nginx or www-data; only the master starts as root so it can bind 80 and 443.
Common pitfalls
- Editing the live file and reloading without
nginx -t. - Putting
streamormailinsidehttp { }. - Forgetting
load_moduleon distro packages. proxy_passtrailing-slash surprises.- Caching
Set-CookieorAuthorizationresponses. - Assuming open-source Nginx actively health-checks backends.
- Using
ip_hashand then removing a server withoutdown, which reshuffles clients. - Expecting the mail proxy to be a mailbox.
Interview FAQ
What is the default load-balancing method? Weighted round robin. least_conn and ip_hash are opt-in.
Round robin vs least_conn vs ip_hash? Round robin (weighted) for even, similar requests. least_conn when some requests are long. ip_hash when you need the same client IP on the same backend (first three IPv4 octets, officially).
How does open-source Nginx notice a dead backend? Passively: max_fails / fail_timeout. Active checks are Plus.
Does the cache always skip the backend? Only on a HIT for a cacheable response. Check X-Cache-Status and the origin's cache headers.
Why won't stream { } parse? Module not compiled or not loaded. Run nginx -V.
Does the mail proxy store mail? No. It requires auth_http and forwards IMAP, POP3, or SMTP to the server that actually holds the mailbox.
Where does TLS belong? Usually on Nginx (termination), sometimes passed through in stream if the backend must see the client certificate or inspect TLS itself.
What does keys_zone size mean? Shared memory for cache keys and metadata, not the on-disk max_size. If the zone is too small, Nginx cannot index everything on disk.
root versus alias? root appends the URI to the path. alias replaces the location prefix. They are not interchangeable without a test.
Layer 7 or layer 4? http and mail are protocol-aware (L7). stream can be L4 forwarding, with optional TLS preread or termination.
How do you drain a backend? Mark it down (required for a stable ip_hash table) or remove it, then nginx -t and reload.
Location matching and request routing
Wrong location matches cause many role-1 and role-2 bugs. Official precedence is:
- Exact match:
location = /path - Longest matching prefix, remembered; a prefix marked
^~wins immediately and skips regex - Regular expressions in the order they appear (
~case-sensitive,~*case-insensitive) - If no regex matches, the remembered prefix is used
location = /healthz { return 200 "ok\n"; add_header Content-Type text/plain; }
location ^~ /static/ { root /var/www/example; expires 30d; }
location ~* \.(php)$ { return 404; } # do not accidentally execute uploads
location /api/ { proxy_pass http://backend; }
Put health checks on an exact location so they never hit a regex or a cache. Prefer prefix + ^~ for static trees. Never hang a proxy_pass off a location that also serves user-uploaded files.
Keepalive, buffers, and WebSockets
Without keepalive, Nginx opens a new TCP connection to the app on every request — fine at low rate, expensive at high rate:
upstream backend {
least_conn;
server 10.0.1.11:8080;
server 10.0.1.12:8080;
keepalive 32;
keepalive_requests 1000;
}
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
proxy_http_version 1.1 and an empty Connection header are required for those keepalive connections. Tune proxy_buffer_size, proxy_buffers, and client_max_body_size to the payloads you actually accept. A default body limit will 413 large uploads; an unlimited one will let a client fill your disk.
WebSockets need an explicit upgrade:
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s;
}
Raise proxy_read_timeout or idle sockets close and the client reconnects in a loop.
Rate limits, access control, and logging
http {
limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=perip:10m;
log_format main '$remote_addr $request $status $body_bytes_sent '
'cache=$upstream_cache_status upstream=$upstream_addr '
'rt=$request_time uct=$upstream_connect_time '
'uht=$upstream_header_time urt=$upstream_response_time';
server {
listen 443 ssl;
location /login {
limit_req zone=auth burst=10 nodelay;
limit_conn perip 10;
proxy_pass http://backend;
}
}
}
$upstream_addr and the timing variables show whether slowness is Nginx, a cache MISS, or the app. limit_req returns 503 by default; set limit_req_status 429 if you prefer that. allow / deny can protect an admin path at the edge; they are not a substitute for application authentication.
TLS passthrough in stream, versus termination
Role 2 terminates TLS in http. Role 5 can instead pass the bytes through so the backend completes the handshake. That is useful when the app must see the client certificate, or when you do not want Nginx to hold the private key:
stream {
map $ssl_preread_server_name $backend {
api.example.com 10.0.4.10:443;
app.example.com 10.0.4.20:443;
default 10.0.4.30:443;
}
server {
listen 443;
ssl_preread on;
proxy_pass $backend;
}
}
ssl_preread reads SNI from the ClientHello and does not decrypt (stream SSL preread module). If you terminate TLS in stream, use listen 5432 ssl; plus stream ssl_certificate directives — a different context from http, even if the files are the same. Dynamic hostname upstreams need a resolver in that context, or Nginx keeps the address it saw at start and misses pod IP changes.
What auth_http actually exchanges
On each IMAP, POP3, or SMTP login, Nginx calls auth_http. Official request headers include the protocol, method, user, and (for SMTP) the sending address. A successful response looks like:
HTTP/1.0 200 OK
Auth-Status: OK
Auth-Server: 10.0.5.20
Auth-Port: 143
Any other Auth-Status is failure; Nginx can pass the text back if proxy_pass_error_message on is set. The response body is ignored. The auth service is a small HTTP app you run — it is not built in — and it chooses which backend owns that mailbox. If it is down, mail login fails even when IMAP is healthy. STARTTLS and implicit TLS are configured per mail server. Do not leave listen 143 open for cleartext passwords.
Production checklist
nginx -V— confirm stream, mail, and SSL modules.nginx -ton every change, thennginx -s reload.- Certificates, TLS policy, and
server_tokens off. proxy_set_headerforHostandX-Forwarded-Proto.proxy_cache_keyincludes host and URI; do not vary on cookies you do not mean to.- Treat
max_fails/fail_timeoutas passive checks. - Logs include
$upstream_cache_statusand$upstream_addr. - Disk room for
proxy_cache_path;max_sizeis a target, and cleanup is periodic. worker_rlimit_nofileand the systemd unit agree withworker_connections.- Rehearse
backupanddown, including theip_hashreshuffle case.
In-flight requests finish on old workers after reload. A certificate permission problem that -t cannot see can still fail new workers — watch error.log for a minute after every change.
Recap
| Role | Official piece | Caption to tighten |
|---|---|---|
| Web server | root, try_files, static location | Accurate for files on disk |
| Reverse proxy | proxy_pass, TLS in the server | Hides the path; still configure headers and networks |
| Cache | proxy_cache_path, proxy_cache | Fast on HIT; not every response is cacheable |
| Load balancer | upstream, weighted RR default | least_conn, ip_hash; passive failovers in OSS |
| TCP/UDP | stream { }, listen … udp | Separate module; may need --with-stream or load_module |
| Mail proxy | mail { }, auth_http | Routes IMAP/POP3/SMTP; does not store mail |
Six jobs, one tool — if the right modules are loaded, the config is tested, and you remember which features are Plus or post-1.31. Follow @rankcore.ai, and read more on blog.rankcore.ai.
Want to go deeper?
Our step-by-step video courses turn these ideas into results.
Comments
No comments yet — be the first.