Skip to content
Cloud, DevOps & Infrastructure

Nginx interview questions and answers

79 questions, 52 with code. About 6 h 41 min to read them all.

By TestLab · Updated

Plan for an interview
79 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What is Nginx and what is it used for?

Nginx is a high-performance, event-driven web server and reverse proxy originally created by Igor Sysoev. Instead of spawning a thread or process per connection, it runs a small number of worker processes, each driven by an asynchronous event loop, which lets it serve tens of thousands of concurrent connections with a modest memory footprint. In production it is most often deployed as a reverse proxy and load balancer in front of application servers, but it also serves static files, terminates TLS, caches responses, and enforces rate limits and security headers.

Read full answer

Applies toNginx 1.24+ (open source stable branch) and Nginx Plus; HTTP/3 requires mainline 1.25+.

Architecture

  • Master process: reads and validates the configuration, binds listening sockets, and manages worker lifecycle. It does not handle client traffic itself.

  • Worker processes: each runs a single-threaded event loop (using epoll on Linux, kqueue on BSD/macOS) and handles many connections concurrently. The number is typically set to auto, matching CPU cores.

  • No thread-per-connection model: connections are multiplexed through non-blocking I/O, which is why Nginx scales well for keep-alive and slow clients.

  • Graceful reload: nginx -s reload starts new workers with the new config while old workers finish in-flight requests, enabling zero-downtime configuration changes.

Common Use Cases

  • Reverse proxy / load balancer: forwards requests to upstream application servers (Node.js, Python, Java, PHP-FPM) with health checks and balancing algorithms.

  • Static content serving: efficiently delivers files, assets, and pre-compressed content directly from disk.

  • TLS termination: centralizes certificate management and offloads cryptographic work from backends.

  • API gateway: applies rate limiting, authentication hooks, request rewriting, and routing by path or host.

  • Caching layer: stores upstream responses to reduce backend load and latency.

  • WebSocket and gRPC proxying: upgrades connections and proxies long-lived streams.

Key Characteristics

  • Declarative configuration: hierarchical contexts (main, http, server, location) with inheritance of directives.

  • Modular design: features such as gzip, caching, and stub_status are compiled in or loaded as dynamic modules.

  • Precise location matching: exact = matches first; then the longest prefix match, with ^~ stopping regex evaluation; otherwise regex locations are tested in declaration order. This is a frequent source of subtle bugs.

  • Upstream abstraction: named upstream groups use default round-robin, with explicit methods such as least_conn, ip_hash, and random.

Advantages and Limitations

Aspect Strength Limitation
Concurrency Excellent under high connection counts Single-threaded workers; CPU-bound work blocks the loop
Memory Low per-connection overhead Large file serving still consumes worker time
Configuration Powerful and expressive Steep learning curve; subtle inheritance rules
Dynamic changes Graceful reload without downtime No runtime config API in open source (Plus has one)
Scripting Limited (njs module) Complex logic often belongs in the app or a gateway

Production Considerations

  • Set worker_processes auto; and size worker_connections to the expected concurrent connection count, remembering that proxying a request uses two connections and therefore two file descriptors.

  • Enable stub_status or the Plus API and export metrics to Prometheus for connection, request, and upstream health monitoring.

  • Use server_tokens off; to avoid leaking version information, and add security headers (Strict-Transport-Security, X-Frame-Options, Content-Security-Policy) at the edge.

  • Use proxy_pass deliberately: when it includes a URI, such as a trailing slash, the matched location prefix is replaced; with no URI, the original request URI is forwarded unchanged.

  • Test every change with nginx -t before reloading, and keep configuration in version control.

  • Plan certificate renewal (for example via ACME) and reload automation; expired certificates are a common incident cause.

  • Note that HTTP/3 (QUIC) support is available in mainline 1.25+; the 1.24 stable branch supports HTTP/1.1 and HTTP/2 only.

2

How does Nginx master-worker architecture work?

Nginx uses a master-worker architecture where a single master process manages configuration and multiple worker processes handle all client connections and request processing. This design isolates privilege separation, enables zero-downtime reloads, and scales across CPU cores.

Read full answer

Applies toNginx 1.24+

Master Process Role

The master process runs as root when binding privileged ports and performs no request processing. Its responsibilities: - Configuration parsing and validation at startup and on reload signals - Worker lifecycle management: spawning, monitoring, and reaping worker processes - Signal handling: translating signals (HUP, QUIT, TERM, USR1, USR2, WINCH) into coordinated worker actions - Privileged operations: binding listen sockets before dropping privileges, opening log files - Shared memory zone initialization for caching, rate limiting, and upstream state

Worker Process Role

Worker processes run as an unprivileged user (typically www-data or nginx) and do all actual work: - Event loop (epoll on Linux, kqueue on BSD) accepting connections on shared listen sockets - Request processing: HTTP parsing, TLS termination, static file serving, reverse proxying, load balancing - Upstream communication: connecting to backend servers, buffering responses - Cache operations: reading/writing to shared memory zones and disk cache - Access logging and metrics emission

Each worker is single-threaded and handles thousands of concurrent connections asynchronously. The default worker_processes auto; sets the count to the number of available CPU cores.

Process Communication

  • Listen sockets: Created by master, inherited by workers via fork(). All workers call accept() on the same sockets; the kernel distributes connections. Distribution can be improved with reuseport on the listen directive, available since Nginx 1.9.1.

  • Shared memory zones: Created by master (proxy_cache, limit_req_zone, upstream state), mapped into each worker for lock-free or mutex-protected access.

  • No direct IPC between workers; coordination happens through shared memory and kernel socket distribution.

Signal Handling

Signal Master Action Worker Action
HUP Re-read config, start new workers with new config, send QUIT to old workers Finish current requests, exit gracefully
QUIT Wait for workers to finish, then exit Stop accepting new connections, finish current requests, exit
TERM / INT Send TERM to all workers, exit immediately Abort current requests, exit immediately
USR1 Reopen log files (log rotation) Reopen log files
USR2 Start new master for binary upgrade — (old workers keep running)
WINCH Send QUIT to workers (graceful shutdown) Graceful shutdown

Configuration Reloading

On HUP (via nginx -s reload): 1. Master parses and validates new configuration 2. If valid, master creates new listen sockets and spawns a new worker set 3. Master sends QUIT to old workers 4. Old workers stop accepting new connections, drain existing requests, then exit 5. New workers take over seamlessly — zero downtime, no connection drops

If validation fails, master logs the error and keeps running with the old configuration.

Best Practices and Operational Considerations

  • Set worker_processes to CPU core count (or auto). More workers than cores adds context-switch overhead; fewer underutilizes hardware.

  • Pin workers to CPUs with worker_cpu_affinity on high-throughput systems to reduce cache misses.

  • Tune worker_connections (default 512) based on ulimit -n and expected concurrency: max_clients = worker_processes × worker_connections.

  • Enable reuseport on listen directives for better connection distribution across workers under high load; it is not enabled by default.

  • Run master as root, workers as an unprivileged user — never run workers as root.

  • Monitor worker count (ps aux | grep nginx) and master PID file (/run/nginx.pid) for process health.

  • Set worker_shutdown_timeout to force-close lingering connections during graceful shutdown and prevent stuck workers from blocking reloads indefinitely.

  • Binary upgrades (USR2 + WINCH + QUIT) allow Nginx executable replacement without downtime — test in staging first.

  • Avoid frequent reloads under extreme load; each reload spawns a full new worker set, temporarily doubling memory and CPU.

3

Why is Nginx event-driven model efficient vs thread-per-connection?

Nginx is efficient because a small number of worker processes each run a single-threaded event loop that multiplexes many connections with non-blocking I/O, instead of dedicating an OS thread or process to every connection.

Read full answer

Applies toNginx 1.24+ (open source)

How It Works

Nginx uses a master/worker architecture. The master process reads configuration, binds listening sockets, and manages worker processes. Each worker runs an event loop and handles many client connections concurrently.

  • Workers use non-blocking sockets and OS event-notification mechanisms such as epoll on Linux and kqueue on BSD/macOS.

  • The kernel reports which sockets are ready for read or write, so a worker processes only ready connections and immediately moves on.

  • If an operation would block, Nginx returns EAGAIN/EWOULDBLOCK and continues serving other connections.

Why It Beats Thread-Per-Connection

Thread-per-connection servers create or reuse an OS thread for each active connection. That model has several costs that grow with concurrency:

Area Event-driven Nginx Thread-per-connection
Memory per connection Small connection state, often a few KB Thread stack plus kernel/user bookkeeping, often much larger
Context switches Fewer, because one thread handles many ready events More, as the scheduler switches between many threads
Blocking behavior Non-blocking; slow clients do not stall workers A blocked thread may sit idle while waiting on I/O
Scaling limit Tens or hundreds of thousands of mostly idle connections Thread count, memory, and scheduler overhead
CPU cache locality Better, because one worker stays on one core More cache churn across many threads

This is the classic answer to the C10K problem: Nginx can hold many keep-alive or slow connections without allocating a thread for each one.

Important Trade-Offs

The event loop is efficient only if workers do not block. A worker that performs synchronous disk I/O, heavy computation, or a long-running module callback can stall every connection assigned to that worker.

  • Set worker_processes auto; so Nginx uses one worker per CPU core.

  • Tune worker_connections based on file-descriptor limits and expected concurrency.

  • Avoid blocking modules or synchronous upstream calls in request paths.

  • Use sendfile, tcp_nopush, and tcp_nodelay appropriately for static-file delivery.

  • For CPU-heavy work, offload it to application servers or background workers rather than doing it inside Nginx.

Production Considerations

  • Monitor active, reading, writing, and waiting connections through stub_status or exporter metrics.

  • Raise worker_rlimit_nofile and system ulimit -n together; otherwise high connection counts fail with “too many open files.”

  • Use graceful reloads with nginx -s reload to avoid dropping connections during config changes.

  • HTTP/2 and HTTP/3 multiplex many streams over fewer connections, which pairs well with the event-driven model.

  • TLS handshakes are CPU-intensive; size worker count and CPU capacity accordingly, and consider session resumption or TLS 1.3 where supported.

Common Pitfalls

  • Assuming “event-driven” means unlimited concurrency; file descriptors, memory, and upstream capacity still limit throughput.

  • Running blocking Lua, Perl, or third-party modules inside workers.

  • Setting worker_processes far above CPU core count, which increases context switching without improving throughput.

  • Ignoring slow clients; even non-blocking servers can accumulate many waiting connections if timeouts are too generous.

4

How does Nginx compare with Apache HTTP Server?

Nginx is an event-driven, high-throughput web server and reverse proxy, while Apache HTTP Server is a highly modular server with extensive configuration and ecosystem support. Both are production-ready, but they optimize for different operational priorities.

Read full answer

Applies toNginx 1.24+ (HTTP/3 from 1.25.0) and Apache HTTP Server 2.4.26+

Architecture and Performance

Area Nginx Apache HTTP Server
Process model One master process manages multiple worker processes Multi-processing Modules: prefork, worker, or event
Concurrency Workers use a non-blocking, event-driven I/O loop prefork uses a process per connection; worker and event use threads
Memory use Generally lower overhead for many concurrent connections Traditionally higher process or thread overhead, depending on MPM
Static content Efficient native handling with sendfile and caching controls Efficient, particularly with mod_autoindex, mod_expires, and related modules
Dynamic execution Usually forwards requests to PHP-FPM, Python, Node.js, or another upstream Can run modules in-process, although PHP-FPM is generally preferred for isolation

Nginx’s event loop is effective for large numbers of mostly I/O-bound connections, such as API traffic, static assets, and TLS termination. It does not make CPU-bound work asynchronous: a slow application or expensive computation can still occupy a worker.

Apache’s event MPM also handles high concurrency, but remains thread-based and has different memory and scheduling characteristics from Nginx’s event loop. Its extensive module ecosystem remains a major advantage: Apache can serve applications through mod_wsgi, mod_proxy_fcgi, or in-process modules, while Nginx normally acts as a front-end proxy.

Configuration and Request Routing

Nginx uses a hierarchical configuration:

  • http: global HTTP settings.

  • server: virtual host and port.

  • location: routing rules for paths.

  • upstream: grouped backend servers.

Nginx location selection checks exact matches such as location = /health, then longest prefix matches, then regular expressions in configuration order. A prefix match with ^~ prevents regular-expression evaluation. If no location matches, Nginx falls back through the server and default location rules.

Apache uses <VirtualHost>, <Directory>, <Location>, <Files>, and related directives. Unlike Nginx, it supports per-directory .htaccess files, which are useful for shared hosting but add permission and configuration checks. Set AllowOverride None where .htaccess processing is unnecessary.

A common Nginx mistake involves the trailing slash on proxy_pass:

  • proxy_pass http://backend; forwards the original request URI.

  • proxy_pass http://backend/; replaces the matched location prefix with /.

For example, a request for /api/orders sent from location /api/ behaves differently between these forms.

Reverse Proxy and Feature Support

Capability Nginx Apache HTTP Server
Reverse proxy proxy_pass; optional upstream groups mod_proxy; mod_proxy_http, mod_proxy_fcgi, and others
Load balancing Round robin, least connections, IP hash, and upstream keepalive mod_proxy_balancer with multiple balancing methods
Health checks Open-source Nginx uses passive handling through max_fails and fail_timeout; active checks require NGINX Plus or a third-party module No general active checker in Apache 2.4; eligible requests can be retried, and mod_proxy_heartbeat can propagate member-status changes
HTTP/2 Native support Supported through mod_http2
HTTP/3 Introduced in Nginx 1.25.0 and available when built with QUIC support; use a current patched release No generally available native HTTP/3 implementation
Caching proxy_cache, FastCGI caching, and uwsgi_cache mod_cache and mod_mem_cache
Compression gzip; Brotli when compiled with the module mod_deflate; Brotli usually requires an external module
Rate limiting limit_req and limit_conn using shared memory zones Bandwidth limiting through mod_ratelimit; request controls are less uniform
Security headers add_header, access controls, and authentication modules mod_headers, authorization modules, and .htaccess rules

Nginx generally offers a more focused reverse-proxy configuration experience. Apache provides more flexibility for legacy applications, authentication workflows, and specialized modules.

Security and Failure Modes

Both servers should terminate TLS with modern ciphers, redirect HTTP to HTTPS, restrict status endpoints and administration, and set application-appropriate security headers. Avoid duplicating headers at Nginx and the upstream unless ownership is explicit, because duplicate Set-Cookie or HSTS headers can cause problems.

Typical failure modes differ:

  • Nginx: worker or file-descriptor exhaustion, unhealthy upstream pools, slow-client resource consumption, and full proxy-cache storage.

  • Apache: exhausted workers or threads, MPM/process limits, slow .htaccess processing, and module-specific memory overhead.

  • Both: certificate expiry, DNS changes that are not propagated, overloaded backends, disk-full logging, and configuration errors causing failed reloads.

A configuration error should be detected before activation. Use sudo nginx -t && sudo nginx -s reload for Nginx and sudo apachectl configtest && sudo apachectl graceful for Apache. During upgrades, test in staging, back up active configuration and TLS private keys to encrypted off-host storage, verify restoration, preserve the previous package or binary, and drain instances gradually behind a load balancer.

Operational Choice

Choose Nginx for high-concurrency reverse proxying, API gateways, static-content delivery, and straightforward upstream load balancing. Choose Apache when existing .htaccess rules, specialized modules, or mixed application hosting are important.

For either server, monitor active connections, latency, error rates, upstream failures, TLS expiry, cache behavior, and disk usage. Nginx exposes stub_status counters only when that module and a restricted location are enabled; Apache provides server-status and optional ExtendedStatus only when configured.

Configure structured access and error logs (access_log/error_log in Nginx; CustomLog/ErrorLog in Apache), centralize them off-host, rotate them, and avoid logging secrets or unnecessary client data. Collect metrics with Prometheus exporters or native platform monitoring, and test configuration changes and recovery procedures before deployment.

5

How is an Nginx configuration organized across contexts and files?

An Nginx configuration is a hierarchy of directives organized into contexts, with the main file including other files to separate virtual hosts, upstreams, TLS material, and shared settings. Context determines where each directive is valid and how it is inherited.

Read full answer

Applies toNginx OSS 1.24+ on Linux

Configuration Hierarchy

The principal contexts are:

Context Purpose
main Global settings such as worker_processes, error_log, pid, and top-level includes
events Worker connection limits and event-handling behavior
http HTTP settings, including server, upstream, map, cache zones, and logging
server A virtual server selected primarily by listening address and port and the request’s Host header
location URI routing and handling within a virtual server
upstream A named group of backend servers used for proxying and load balancing

A separate top-level stream context handles TCP and UDP proxying. Nginx also has nested contexts such as if, limit_except, and types.

Many directives are inherited from an outer context and can be overridden in a nested context, although behavior is directive-specific. For example, worker_connections belongs in events, while proxy_pass belongs in location rather than directly in server.

The main configuration is conventionally /etc/nginx/nginx.conf. include can be used in applicable contexts, commonly from main or http. RHEL-style packages commonly use /etc/nginx/conf.d/*.conf; Debian and Ubuntu commonly use /etc/nginx/sites-enabled/*. Packaging differs, so verify the installed nginx.conf rather than assuming a layout.

Include order can be significant: regular-expression locations are checked in configuration order, and the first server for an address and port generally becomes the default server. Some directives append or aggregate entries, while duplicate scalar directives may be rejected.

Request and Location Matching

For requests on the same listening address and port, Nginx matches the Host header against server_name: exact names are preferred, followed by the longest applicable wildcard and then regular expressions in configuration order. If none matches, the default server is used.

Within the selected server, locations are evaluated as follows:

  1. An exact match such as location = /healthz wins immediately.

  2. Nginx identifies the longest matching prefix location.

  3. If that prefix uses ^~, it is used without checking regular expressions.

  4. Otherwise, regular-expression locations are tested in configuration order; the first match wins.

  5. If no regular expression matches, the longest prefix location is used.

A regular-expression location can therefore take precedence over a longer prefix unless that prefix uses ^~.

Reverse Proxy and Upstream Behavior

The trailing slash on proxy_pass changes URI rewriting:

Configuration Backend URI
location /api/ { proxy_pass http://backend; } Preserves the original /api/... URI
location /api/ { proxy_pass http://backend/; } Replaces the matched /api/ prefix with /

Backends must agree on the path they receive. Set the Host, X-Real-IP, X-Forwarded-For, and X-Forwarded-Proto headers explicitly when the application depends on them.

An upstream group normally distributes requests using weighted round-robin; alternatives include least_conn and ip_hash. OSS Nginx performs passive failure handling rather than active health checks. Upstream keepalive requires HTTP/1.1 to the backend and normally includes proxy_http_version 1.1 and an empty Connection header.

Other Common Configuration Areas

  • Static content: root, alias, try_files, and index serve files. Workers need filesystem permissions, and SELinux or container mount policies must allow access. Use browser or CDN caching for immutable assets.

  • TLS and protocols: ssl_certificate and ssl_certificate_key belong in the relevant server. Restrict protocols and protect private keys. HTTP/2 can be enabled for TLS listeners. Native HTTP/3 first appeared in Nginx 1.25, was experimental in 1.25.0, and requires a compatible QUIC build, TLS stack, clients, and UDP firewall access.

  • Caching and compression: Define proxy_cache_path under http, then enable proxy_cache where required. gzip and gzip_types compress eligible responses but consume CPU and should not recompress already-compressed assets.

  • Rate limiting: Define limit_req_zone under http and apply limit_req in protected contexts. limit_conn_zone controls concurrent connections and is a separate mechanism.

  • Security headers and logging: add_header can set headers such as X-Content-Type-Options, Referrer-Policy, and CSP. Parent-level add_header directives are not inherited when the current level defines any add_header. Use log_format and access_log for request telemetry and rotate logs in production.

Production Operations and Pitfalls

  • Architecture: The master process reads configuration and manages workers. Workers use an event-driven, non-blocking model to handle many connections. worker_processes auto sizes the worker count from available CPUs.

  • Validation and reloads: Run sudo nginx -t before every reload and sudo nginx -T to inspect the fully expanded configuration. sudo systemctl reload nginx starts a graceful reload, though existing connections can delay old workers from exiting.

  • Monitoring: Track error logs, upstream timeouts, 499, 502, 503, and 504 responses, request latency, active connections, cache behavior, and disk usage for logs and caches.

  • Failure prevention: Back up configuration and TLS material, test upgrades in staging or a canary environment, and monitor rate-limit rejections. Separate unrelated routes with explicit blocks so configuration changes remain narrowly scoped, while recognizing that locations do not isolate worker-process failures.

6

What are Nginx main, events, http, server, and location contexts?

Nginx contexts are configuration scopes that determine where directives may appear and how they are inherited. main is the implicit top-level scope; it contains separate events and http blocks, http contains server blocks, and server contains location blocks.

Read full answer

Applies toNginx 1.24+

Context Hierarchy

Context Purpose Typical directives
main Process-wide configuration user, worker_processes, worker_rlimit_nofile, pid, error_log
events Configures the event-driven connection-handling method worker_connections, multi_accept, use
http Groups HTTP-specific configuration server, upstream, log_format, gzip, proxy_cache_path
server Defines a virtual host for a listening address and port listen, server_name, root, location
location Selects handling for a URI path within a server proxy_pass, root, try_files, index, rewrite

The main context has no braces; it is the implicit top-level scope. The events block is required in a normal Nginx configuration. These are not the only contexts: upstream, for example, defines groups of HTTP upstream servers.

Process Architecture

Nginx normally runs a master process and one or more worker processes:

  • The master reads the configuration, creates listening sockets, manages workers, and handles signals such as reload and shutdown.

  • Workers accept and process connections using an event-driven model. Nginx normally uses epoll on Linux and mechanisms such as kqueue on other platforms.

  • worker_processes auto selects a worker count based on available CPU resources.

  • worker_connections limits the simultaneous connections a worker can have open. Operating-system file-descriptor limits can become the practical constraint first.

  • events controls connection processing; it does not define HTTP request routing.

Server and Location Selection

When multiple servers share an address and port, Nginx selects one by exact server_name, then the longest wildcard name, then the first matching regular expression in configuration order. default_server is the fallback for that address and port and should normally appear only once per address and port.

Within a server, location selection follows this order:

  1. An exact match using location = /path wins immediately.

  2. Nginx finds the longest matching prefix location.

  3. Unless that prefix uses ^~, regular-expression locations are tested in configuration order.

  4. If no regular expression matches, Nginx uses the longest prefix location.

Query-string parameters do not participate in location matching. Nginx normalizes the URI before matching by decoding applicable escapes and resolving path components. Internal redirects can restart location selection.

Inheritance and Proxy URI Handling

Directives are inherited only when their documented contexts permit it and the child scope does not override them. Thus, suitable http directives can reach server and location, while suitable server directives can reach their locations. Inheritance is directive-specific: defining any add_header at the current level prevents inheritance of all higher-level add_header directives.

proxy_pass URI handling depends on both the URL and location type:

  • proxy_pass http://upstream; forwards the request URI as sent by the client; if rewriting or an internal redirect changed it, the full normalized URI is forwarded.

  • In a prefix location, proxy_pass http://upstream/; replaces the matched location prefix with /. Under location /api/, a request for /api/users becomes /users upstream.

  • A URI component is prohibited when proxy_pass is used inside a regular-expression or named location.

Placement of Common Features

Feature Correct placement and behavior
Static files Use root, index, and try_files in server or location; use alias carefully because it changes path mapping.
Reverse proxy Use proxy_pass and proxy_set_header in server or location.
Load balancing Define HTTP upstream groups under http, then reference them from proxy_pass.
TLS Configure certificates, protocols, and ciphers at http or server scope.
HTTP/2 Nginx 1.24 supports listen 443 ssl http2;. From 1.25.1, the recommended form is http2 on;.
HTTP/3 Nginx OSS 1.25+ requires an HTTP/3/QUIC-enabled build and corresponding server configuration.
Caching Define zones with proxy_cache_path under http; enable them with proxy_cache.
Compression Configure gzip or gzip_static at the appropriate http, server, or location level.
Rate limiting Define shared zones with limit_req_zone under http; apply limit_req in server or location.
Security and logging Use add_header for security headers, define log_format under http, and configure access_log and error_log at suitable scopes.

Production Operations

Validate changes with sudo nginx -t; use sudo nginx -T to validate and display the complete configuration, including included files. A reload with sudo nginx -s reload or sudo systemctl reload nginx starts new workers with the new configuration while old workers finish serving existing clients.

Configuration testing does not prove upstream reachability, certificate validity, or firewall access. Monitor access and error logs, upstream latency, connection and request rates, certificate expiry, and worker or file-descriptor exhaustion. Back up configuration, included files, certificates, and private keys; restrict private-key permissions. Validate upgrades in staging and retain a tested rollback package because directive support and defaults can change between release branches.

7

How does Nginx choose a server block for a request?

Nginx performs server block selection in two stages: it first associates the connection with a listening socket, then matches the request authority against the server_name values configured for that socket. If no name matches, the default server for that listen address and port handles the request.

Read full answer

Applies toNginx 1.24+ (open source)

Request Path and Architecture

Nginx configuration is hierarchical: main → http → server → location. The master process reads the configuration, binds listening sockets, and manages worker processes. Worker processes accept connections and use an event-driven architecture to handle many connections without dedicating a process to each one.

For each connection, Nginx identifies the matching listen address and port. Server blocks sharing that socket form the candidate set. A wildcard listen such as 0.0.0.0:80 covers addresses not bound by a more specific listener.

Server-Name Selection

After reading the request headers, Nginx applies these priorities among the candidate server blocks:

Priority Match type Example
1 Exact server_name example.com
2 Longest wildcard beginning with * *.example.com
3 Longest wildcard ending with * mail.*
4 First matching regular expression ~^www..+$
5 Default server for the listen socket default_server

The compared value normally comes from the HTTP Host header. HTTP/2 and HTTP/3 use :authority, which Nginx handles equivalently for virtual-server selection. If the request has no usable authority, or no configured name matches, Nginx uses the default server.

For TLS, SNI is examined during the handshake and can select the SSL configuration and certificate. Once HTTP headers arrive, Host or :authority can still select the virtual server that handles the request, potentially differing from the SNI-selected server. SNI, authority, certificates, and proxy configuration must therefore be consistent. Without SNI, the default server’s certificate is presented.

Location Selection

Location selection happens after the server block has been selected:

  1. An exact location = /path match wins immediately.

  2. Otherwise, Nginx remembers the longest matching prefix location.

  3. A prefix marked ^~ prevents regular-expression locations from being checked.

  4. Without ^~, regular-expression locations are tested in configuration order, and the first match wins.

  5. If no regular expression matches, the remembered longest prefix is used.

This distinction matters when one server contains several location blocks with different proxy, static-file, and caching behavior.

Production Behavior

  • Static content: root and try_files serve files directly; missing files should normally return a deliberate status such as 404 rather than being proxied accidentally.

  • Reverse proxy: proxy_pass sends the request upstream. With a URI such as proxy_pass http://upstream/, the matched location prefix is replaced; without a URI, the original normalized request URI is passed.

  • Load balancing: upstream groups peers and uses round-robin selection by default. Open-source Nginx performs passive failure detection rather than active health checks.

  • TLS and protocols: HTTP/2 is supported throughout this range; Nginx 1.25.1 introduced the newer http2 on; syntax while retaining the deprecated listen ... http2 form temporarily. HTTP/3 support starts with Nginx 1.25.0 and requires a build with HTTP/3 support and suitable TLS/QUIC support.

  • Caching and compression: proxy_cache caches eligible upstream responses, while gzip compresses suitable response types. Cache keys, exclusions, disk capacity, and invalidation must be planned explicitly.

  • Rate limiting and security: limit_req_zone plus limit_req controls request rates, and add_header can add headers such as X-Content-Type-Options and Referrer-Policy.

  • Logging: Use access and error logs, normally including the upstream status, request time, and relevant routing fields. Include the request authority and selected server when troubleshooting virtual-host behavior.

Operational Guidance and Pitfalls

  • Define an explicit default_server for each listen address and port. If none is specified, the first server configured for that socket becomes the implicit default.

  • Treat server_name _; as a readability convention only. It does not wildcard-match every hostname; the default server performs the catch-all role.

  • Remember that regular expressions are checked after exact and wildcard matches and are resolved in effective configuration order, including include ordering.

  • Preserve the original authority at an upstream load balancer. When Nginx proxies to an application, use proxy_set_header to send the intended host, commonly $host.

  • Validate with nginx -t, inspect the effective configuration with nginx -T, and apply changes with systemctl reload nginx. A reload starts new workers while old workers finish existing connections.

  • Test HTTP routing with curl -H 'Host: example.com' http://127.0.0.1/; for TLS virtual hosts, use curl --resolve to select both the tested hostname and destination address.

  • Back up configurations and certificates, test upgrades in staging, and monitor error rates, upstream failures, TLS handshakes, cache behavior, rate-limit rejections, and worker saturation during rollout or incidents.

8

What is default_server in Nginx and why define it?

default_server is a parameter on Nginx’s listen directive that designates which server block handles requests whose Host header matches no configured server_name for a given address and port. Defining it explicitly prevents Nginx from silently falling back to the first loaded server block, which is a common source of misrouted traffic and information leakage.

Read full answer

Applies toNginx 1.24+ (open source).

How It Works

When a request arrives, Nginx first selects the listening socket by address and port, then chooses a server block by matching the Host header against server_name entries. If no name matches, Nginx uses the default server for that socket. If you never mark one with default_server, Nginx implicitly makes the first server block in configuration order the default, which is rarely what you intend and can change silently when files are reordered or included.

Only one server block may be default_server per address:port combination; nginx -t rejects duplicates.

Why You Should Define It

  • Predictable routing. Unmatched hosts (scanners, misconfigured clients, stale DNS) hit a block you control instead of your primary site.

  • Information hiding. Without a catch-all, the first vhost’s content and headers can leak to arbitrary Host values, aiding reconnaissance.

  • Cleaner logs. A dedicated default block lets you log or drop junk traffic separately from real traffic.

  • Incident safety. During partial config rollouts or broken includes, an explicit default prevents a random vhost from becoming the public face of the server.

TLS Considerations

For HTTPS, the HTTP Host header is available only after TLS is established. TLS server selection uses SNI, and if no SNI or server name matches, Nginx uses the default server for that socket, so the default server must present a certificate. Two common approaches:

  • Present a dummy or self-signed certificate and return 444 or 404.

  • Use ssl_reject_handshake on; (Nginx 1.19.4+) so unknown SNI names fail the handshake outright, which is cleaner and avoids serving any certificate.

Common Mistakes

  • Forgetting IPv6: listen 80 default_server; alone does not cover [::]:80; add both.

  • Marking multiple blocks default_server on the same port, which fails nginx -t.

  • Relying on server_name _; alone: the underscore is just a never-matching name, not a special catch-all keyword. The default_server flag on listen is what actually makes it the fallback.

  • Placing the catch-all in a file that sorts after the real vhost and assuming order matters; with default_server it does not.

Best Practices

  • Create one explicit catch-all per port that returns 444 (drop connection) or 410 Gone for unknown hosts.

  • Keep the catch-all’s logs separate or disable access logging for noise reduction.

  • For TLS, prefer ssl_reject_handshake on; on modern Nginx to avoid certificate exposure.

  • Always run nginx -t after edits and reload with nginx -s reload.

9

How does Nginx match request URIs to location blocks?

Nginx selects a location block by comparing the normalized request URI against configured patterns in a fixed priority order; the winning block depends on the modifier used (=, ^~, ~, ~*, or none).

Read full answer

Applies toNginx 1.24+ (open source and NGINX Plus)

How It Works

When a request arrives, Nginx first normalizes the URI by decoding %XX sequences, resolving . and .. references, and collapsing adjacent slashes. It then selects the server block using the Host header and runs the location algorithm against that server’s configuration. The algorithm is not simply “first match in file order”; modifiers change priority.

Matching Order

  1. Exact match = — checked first. If it matches, selection stops immediately.

  2. Longest prefix match — all prefix locations, including ^~, are compared, and the longest matching prefix is remembered.

  3. ^~ short-circuit — if that longest prefix used ^~, regex locations are skipped and it wins.

  4. Regex locations — ~ (case-sensitive) and ~* (case-insensitive) are tested in the order they appear in the configuration; the first match wins.

  5. Fallback — if no regex matched, the remembered longest prefix location is used.

Modifiers

Modifier Meaning Stops regex check?
= Exact string match Yes, highest priority
^~ Prefix match preferred over regex Yes
(none) Prefix match No
~ Case-sensitive regex Tested in file order
~* Case-insensitive regex Tested in file order

Common Pitfalls

  • Regex order matters: unlike prefix matches, regex locations are evaluated top-to-bottom, so a broad ~ \.php$ placed before a more specific one can shadow it.

  • Trailing slash mismatch: location /api/ does not match /api; a request to /api may be handled by a broader prefix location or result in 404.

  • proxy_pass URI interaction: a trailing slash in proxy_pass replaces the matched location prefix before forwarding, which is a frequent source of 404s.

  • Nested locations: a matched prefix location can contain nested location blocks, which are evaluated only after the outer one wins; deep nesting makes debugging harder.

  • Case sensitivity: URI matching is case-sensitive by default; use ~* only when case-insensitive matching is genuinely required.

Best Practices

  • Use exact matches (=) for health checks and well-known paths.

  • Use ^~ for static asset prefixes to avoid regex overhead.

  • Group regex locations and order them from most specific to least specific.

  • Test changes with nginx -t and inspect the effective configuration with nginx -T before reloading.

  • Validate real paths with curl -i, including edge cases such as /api versus /api/.

10

How does Nginx match exact, prefix, and regex locations?

Nginx location precedence is: an exact (=) match first, then the longest prefix match, then the first matching regular expression, and finally the longest prefix as a fallback. A ^~ prefix match stops evaluation before regular expressions are considered.

Read full answer

Applies toNginx OSS 1.24 and later

Matching Order

Location selection occurs inside the server block already selected for the request. The normalized request path is matched; the query string does not participate.

Step Match type Result
1 Exact: location = /path Wins immediately, regardless of configuration order
2 Longest prefix Selected as the candidate prefix location
3 Regex: ~ or ~* The first matching regex in configuration order wins
4 Prefix fallback If no regex matches, Nginx uses the previously selected longest prefix

A longest prefix does not automatically beat a regex. Regex locations are checked after the longest prefix has been found, unless that prefix uses ^~.

Location Modifiers

  • Exact match — location = /health: Matches only /health. It has the highest precedence and is useful for fixed health-check or API endpoints.

  • Prefix match — location /assets/: Matches any path beginning with /assets/. Prefix matching is string-based rather than path-segment-based.

  • Prefix with regex exclusion — location ^~ /static/: If /static/ is the longest prefix, Nginx uses it without checking regex locations.

  • Case-sensitive regex — location ~ \.php$: Regex locations are tested in their order of appearance in the configuration. The first match wins.

  • Case-insensitive regex — location ~* \.(?:png|jpg)$: Same ordering behavior, but matching ignores letter case.

For example, /assets/logo.png matches the prefix location /assets/, but it also matches a later PNG regex. Without ^~, the regex location wins. Adding ^~ to /assets/ prevents that regex from being considered.

Code Example

The following is a complete configuration demonstrating the behavior:

worker_processes auto;
error_log stderr;
pid /tmp/nginx-location.pid;

events {
    worker_connections 1024;
}

http {
    log_format location_debug
        '$request_method $uri $status $upstream_addr';
    access_log /tmp/nginx-access.log location_debug;

    upstream app_backend {
        server 10.0.0.10:8080;
    }

    server {
        listen 8080;
        server_name example.com;

        # Exact match has the highest precedence.
        location = /health {
            return 200 "ok\n";
        }

        # This prefix bypasses regex matching for /static/ paths.
        location ^~ /static/ {
            root /var/www/example;
        }

        # A normal prefix: a matching regex can still take precedence.
        location /assets/ {
            proxy_pass http://app_backend;
        }

        # Regex locations are checked in configuration order.
        location ~* \.(?:png|jpe?g)$ {
            proxy_pass http://app_backend;
        }

        # Longest-prefix fallback.
        location / {
            proxy_pass http://app_backend;
        }
    }
}

Validate and run the example:

# Validate syntax and configuration references.
sudo nginx -t -c /tmp/nginx-location.conf

# Start Nginx using the example configuration.
sudo nginx -c /tmp/nginx-location.conf

# Verify the exact location.
curl -i http://127.0.0.1:8080/health

# Reload gracefully after configuration changes.
sudo nginx -t -c /tmp/nginx-location.conf
sudo nginx -s reload -c /tmp/nginx-location.conf

For a production installation managed under /etc/nginx/nginx.conf, use sudo nginx -t && sudo nginx -s reload after validating the changed configuration.

Production Behavior and Pitfalls

  • Proxy path handling: In a prefix location, proxy_pass http://app_backend; passes the original request URI. proxy_pass http://app_backend/; replaces the matched location prefix with /. For example, /api/users becomes /users with the trailing-slash form. Nginx does not permit a URI component on proxy_pass inside a regex location.

  • Regex ordering changes: Moving a regex location earlier can silently route existing endpoints elsewhere. Review regex order during every configuration change.

  • Security boundaries: A broad regex such as location ~ /admin can unintentionally match paths such as /administrator. Use an exact location or a carefully scoped ^~ prefix for protected paths.

  • Performance: Regex matching consumes more CPU than exact or prefix matching. Use ^~ when a whole subtree has a fixed handling policy.

  • Architecture: The Nginx master process reads the configuration and manages workers. Worker processes handle connections through an event-driven event loop, so location matching occurs without creating a thread per connection.

  • Reloads and rollback: nginx -t should precede a reload because the master can retain the old configuration if the new one is invalid. Keep configuration under version control and back up changes before production deployment.

  • Troubleshooting: Use nginx -T to dump the complete active configuration, and log $uri to see the normalized path used for location matching. $request_uri preserves the original request URI and query string, making the two values useful when diagnosing proxy-routing issues.

11

What does the ^~ modifier do in Nginx location blocks?

The ^~ modifier makes a prefix location block take precedence over regular-expression location blocks when it is the longest prefix match.

Read full answer

Applies toNginx 1.24+ (open source)

How Location Matching Works

Nginx chooses a location in this order:

  1. An exact match with = wins immediately.

  2. Nginx finds the longest prefix match among normal and ^~ prefix locations.

  3. If that longest prefix match uses ^~, Nginx uses it and does not test regex locations.

  4. Otherwise, Nginx tests regex locations (~ and ~*) in configuration order and uses the first match.

  5. If no regex matches, Nginx uses the remembered longest prefix match.

So ^~ does not change prefix matching itself; it changes what happens afterward by skipping regex evaluation.

What ^~ Is Useful For

  • Serving static assets from a prefix such as /assets/ without letting a later regex location override it.

  • Avoiding accidental matches from broad regex locations such as location ~ \.php$.

  • Making routing intent explicit when a prefix should always win.

For example, a request for /static/logo.png can match location ^~ /static/ as the longest prefix. Because that location has ^~, Nginx does not evaluate an image regex location and instead serves the file from the configured root for /static/.

Common Pitfalls

  • ^~ is not a regex modifier. It is still a prefix match.

  • ^~ does not beat an exact = match.

  • A shorter ^~ location does not beat a longer normal prefix match unless it is itself the longest prefix match.

  • Prefix matching is case-sensitive, so /Static/ will not match location ^~ /static/.

  • Adding ^~ to every location is unnecessary and can hide intended regex behavior.

Best Practices

  • Use ^~ deliberately for prefixes that must bypass regex locations.

  • Keep regex locations specific and ordered carefully.

  • Run nginx -t after changing location rules.

  • Test routing with curl -I or access logs before deploying to production.

12

How do root and alias differ in Nginx?

root and alias determine how Nginx maps a matched request URI to a filesystem path. root appends the normalized URI to a base directory, while alias substitutes a location-specific path and replaces the matched location prefix.

Read full answer

Applies toNginx 1.24+ on Linux

Core Difference

Directive Valid context Path construction
root http, server, and location Base directory plus the normalized request URI
alias location only Alias path plus the URI remainder after a matched prefix; regex locations can also use captured values

For example, a location /static/ with root /srv/www maps /static/app.css to /srv/www/static/app.css. In contrast, a location /media/ with alias /srv/media/ maps /media/app.css to /srv/media/app.css.

  • root inheritance: A location inherits root from its enclosing server or http block unless it defines its own value.

  • alias scope: alias is valid only in a location and takes precedence over an inherited root for that location.

  • alias matching: The directive changes the filesystem mapping, not which requests match the location.

Location and Path Construction

Nginx evaluates locations in a defined order:

  • An exact match using = wins immediately.

  • Otherwise, Nginx remembers the longest matching prefix location.

  • Regex locations are tested in their configuration order, and the first matching regex normally wins.

  • If the longest prefix location uses ^~, Nginx skips regex-location testing and uses that prefix location.

For prefix locations, alias replaces the matched prefix with the alias path. For regex locations, the alias can contain capture references from the matched location. This distinction matters when constructing paths from request data.

Trailing-Slash and try_files Pitfalls

For prefix locations, keep the location and alias boundaries aligned. A location /media/ with alias /srv/media/ maps /media/app.css to /srv/media/app.css. If the alias lacks the final slash, the URI remainder can be concatenated directly to the alias text, producing paths such as /srv/mediaapp.css.

try_files checks paths using the applicable root or alias mapping. Combining alias with fallback lists can therefore be less obvious than using root, so test the complete mapping and avoid assumptions based only on $uri.

Production Behavior and Failure Modes

Nginx uses a master process to manage workers and an event-driven worker architecture to handle requests and static files. Static delivery can also use sendfile when enabled.

Common production symptoms include:

  • 404 Not Found: The mapped file does not exist, commonly because root includes the location prefix or an alias points to the wrong directory.

  • 403 Forbidden: Workers cannot traverse or read the path, or SELinux denies access.

  • Unexpected content: The mapping resolves successfully but reaches an unintended file.

  • Fallback surprises: try_files combines path construction with alias replacement differently from a simple root mapping.

Monitor access_log and error_log for abnormal 404 and 403 rates, distinguish missing files from permission failures, and test mappings with representative URLs. Include Nginx configuration in configuration management and backups so emergency changes can be reproduced or reverted.

Security and Operational Guidance

  • Restrict each alias to the smallest directory required.

  • Avoid exposing application configuration, source code, secrets, or unrestricted user-upload directories.

  • Prefer separate, narrowly scoped locations for public assets and uploaded content.

  • Validate configuration with sudo nginx -t before running sudo nginx -s reload.

  • Test representative paths with curl -I after deployment.

  • Apply caching, compression, TLS, and security headers independently of whether a static location uses root or alias.

13

What does try_files do in Nginx?

try_files tests a list of file (and directory) paths in order and serves the first one that exists; if none exist, it performs an internal redirect to the final argument, which can be a URI, a named location, or an HTTP status code.

Read full answer

Applies toNginx 1.24+ (open source) and Nginx Plus R31+.

How It Works

  • For each candidate, Nginx builds a filesystem path from the active root or alias plus the argument (commonly $uri or $uri/).

  • It performs existence checks (stat) in the given order.

  • The first existing file is served immediately.

  • The last argument is not checked as a file; it is the fallback used only when all earlier candidates are missing.

  • A fallback URI triggers an internal redirect, so location matching runs again. A named location (@name) jumps directly to that block. =code returns that status without further processing.

Syntax and Arguments

Form Meaning
try_files $uri $uri/ /index.html; Serve file, then directory, else internal redirect to /index.html
try_files $uri $uri/ @backend; Serve file/directory, else jump to named location @backend
try_files $uri =404; Serve file or return 404

Common Patterns

  • SPA fallback: try_files $uri $uri/ /index.html; so client-side routing works while real assets are served directly.

  • Static-first with API fallback: check the file, then hand off to a named location that proxies to an application server.

  • Explicit 404: try_files $uri =404; to avoid accidental fallbacks.

Pitfalls and Best Practices

  • Do not mix a fallback URI with proxy_pass in the same location expecting it to proxy; the fallback URI causes an internal redirect and re-runs location matching, which can loop or hit the wrong block.

  • Named locations are the clean way to proxy after try_files.

  • $uri/ checks directories, so it is useful when you want directory existence to be considered before the fallback.

  • Every candidate costs a stat, so long lists add latency on high-traffic paths; keep the list short.

  • root vs alias matters: try_files builds paths from whichever is active in the location; with alias, the mapping differs and a misplaced slash is a common source of 404s.

  • The last argument is never existence-checked, so a typo there silently becomes the fallback behavior rather than a 404.

  • Validate with nginx -t and reload with nginx -s reload; watch error.log for repeated internal redirects during incidents.

14

How does Nginx serve static files efficiently?

Nginx serves static files efficiently by combining kernel-level sendfile, open-file caching, and zero-copy I/O so file data avoids an unnecessary user-space round trip, while correct cache headers and compression reduce repeat transfers.

Read full answer

Applies toNginx 1.24+ (open source).

How It Works

  • The master process manages workers; each worker runs a single-threaded event loop that handles many connections concurrently without blocking.

  • With sendfile on, Nginx asks the kernel to copy file bytes directly from the page cache to the socket, avoiding a user-space read/write round trip.

  • tcp_nopush on (used with sendfile) coalesces headers and file data into fewer packets; tcp_nodelay on then flushes the last partial packet promptly.

  • open_file_cache keeps file descriptors and metadata (size, mtime) in memory, avoiding repeated stat()/open() syscalls for hot files.

Key Directives

  • sendfile on; — enable kernel sendfile; the single biggest throughput win for static content.

  • tcp_nopush on; / tcp_nodelay on; — packet coalescing plus timely final flush.

  • open_file_cache max=1000 inactive=20s; with open_file_cache_valid, open_file_cache_min_uses, and open_file_cache_errors on; — cache descriptors and negative lookups.

  • aio threads; (optional) — offloads blocking disk I/O to a thread pool for large or slow disks; useful when sendfile is not enough.

  • directio 4m; — bypass page cache for very large files to avoid evicting hot cache.

Location Matching and Path Resolution

  • root /var/www/static; appends the full URI to the path (/assets/x.css → /var/www/static/assets/x.css).

  • alias /var/www/static/; replaces the matched location prefix; the trailing slash must match on both sides or paths break.

  • try_files $uri $uri/ =404; safely resolves files and returns 404 instead of leaking directory listings.

Caching and Compression

  • expires 30d; plus add_header Cache-Control "public, immutable"; lets browsers and CDNs reuse assets; use content-hashed filenames so immutable caching is safe.

  • Nginx emits ETag and Last-Modified by default for static files, enabling conditional 304 Not Modified responses.

  • gzip on; with gzip_types and gzip_min_length compresses text assets; pre-compress with gzip_static on; to serve .gz files directly.

Best Practices and Common Pitfalls

  • Always run nginx -t before reload; a bad alias slash mismatch silently 404s every asset.

  • Do not enable gzip on already-compressed formats (images, video, .gz); it wastes CPU.

  • Set access_log off; for high-traffic static locations to reduce disk I/O.

  • Monitor open_file_cache hit rates and 404 rates; a sudden 404 spike usually means a deploy changed paths or an alias/root mismatch.

  • For very large files, combine aio threads; with directio and test throughput rather than assuming sendfile alone is optimal.

  • Keep static assets on fast local storage or a CDN; Nginx is not a substitute for object storage at scale.

15

How do you set up Nginx reverse proxying for backend services?

Nginx acts as a reverse proxy by accepting public HTTP requests and forwarding them to one or more backend servers through proxy_pass. A production setup should also handle TLS, upstream load balancing, timeouts, rate limiting, observability, and safe forwarding of client metadata.

Read full answer

Applies toNginx 1.24+; HTTP/3 details apply to Nginx 1.25.0+

How It Works

Nginx uses a master process and multiple worker processes. The master reads the configuration and manages workers; each worker uses an event-driven, non-blocking model to handle many connections and upstream requests efficiently.

The request path is:

  1. The client connects to a Nginx server block.

  2. Nginx selects a matching location.

  3. proxy_pass selects an upstream server.

  4. Nginx forwards the request and returns the backend response, commonly after buffering it.

The example below uses least_conn load balancing and passive failure detection. Round robin is the default upstream selection method, while ip_hash can provide session affinity at the cost of uneven distribution.

Code Example

Save this as /etc/nginx/nginx.conf, after provisioning the certificate files:

worker_processes auto;

events {
    worker_connections 4096;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format proxy '$remote_addr $host "$request" $status '
                     '$request_time $upstream_response_time $upstream_addr';
    access_log /var/log/nginx/access.log proxy;

    sendfile on;
    keepalive_timeout 65;
    client_max_body_size 10m;

    gzip on;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript;

    limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;

    upstream app_backend {
        least_conn;
        server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
        server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;
        return 301 https://example.com$request_uri;
    }

    server {
        listen 443 ssl http2;
        server_name example.com;

        ssl_certificate     /etc/nginx/ssl/example.com/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/example.com/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 1d;
        ssl_session_tickets off;

        add_header Strict-Transport-Security "max-age=31536000" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;

        location / {
            limit_req zone=per_ip burst=20 nodelay;
            limit_req_status 429;

            proxy_pass http://app_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";

            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 X-Forwarded-Host $host;

            proxy_connect_timeout 5s;
            proxy_read_timeout 30s;
            proxy_send_timeout 30s;
            proxy_buffering on;
        }
    }
}

Validate and activate the configuration:

sudo nginx -t
sudo systemctl reload nginx

The listen ... http2 syntax works for Nginx 1.24+. On Nginx 1.25.1+, the preferred form is listen 443 ssl; together with http2 on;. HTTP/3 requires listen 443 quic reuseport;, http3 on;, a compatible Nginx build, and clients and firewalls permitting UDP 443.

Routing and Forwarding Semantics

Location selection is deterministic:

Location form Behavior
location = /health Exact match has highest priority
location ^~ /assets/ Prefix match stops regular-expression checks
location ~ .php$ Regular expressions are evaluated in configuration order
location /api/ Longest matching prefix is used when nothing more specific matches

The trailing slash on proxy_pass changes URI replacement:

Configuration Request Backend URI
location /api/ + proxy_pass http://app_backend; /api/orders /api/orders
location /api/ + proxy_pass http://app_backend/; /api/orders /orders

Query strings are preserved. This difference is a frequent source of incorrect API routing.

Protocols, Caching, and Static Files

HTTP/2 and HTTP/3 terminate at Nginx; the upstream connection in this example remains HTTP/1.1. WebSocket locations need different handling: preserve the client’s Upgrade and Connection headers and normally disable response buffering there.

Nginx can serve static files directly from a root or alias, avoiding unnecessary backend traffic. proxy_cache_path and proxy_cache can cache backend responses, but authenticated or personalized responses require careful cache keys and purging. The example enables gzip compression; Brotli requires an additional compatible module.

Failure Modes and Operations

  • 502 Bad Gateway: Nginx cannot connect to the backend or receives an invalid upstream response. Check firewall rules, listener addresses, DNS, and upstream logs.

  • 504 Gateway Timeout: The backend accepted the request but did not respond before proxy_read_timeout. Long-running APIs need appropriately coordinated timeouts.

  • 429 Too Many Requests: The configured limit_req limit was exceeded. burst allows temporary excess, while nodelay processes it immediately.

  • Streaming delays: proxy_buffering on can delay streamed responses or consume memory and temporary disk space.

  • DNS changes: Upstream hostnames are resolved when the configuration loads. Reload Nginx after changing the resolved addresses.

  • Capacity: Monitor upstream latency, Nginx CPU and memory, request rates, 4xx/5xx responses, and active and queued connections.

  • Upgrades: Run nginx -t, reload gracefully, monitor error rates, and retain the previous configuration for rollback.

  • Certificates: Back up and protect private keys, automate renewal, and reload Nginx after renewal.

Security and Operational Best Practices

  • Restrict backend ports to networks that can reach Nginx; do not expose application servers directly to the internet.

  • Trust X-Forwarded-For only from a known proxy. Behind a trusted load balancer in 10.0.0.0/16, configure set_real_ip_from 10.0.0.0/16, real_ip_header X-Forwarded-For, and real_ip_recursive on.

  • Apply request-size limits and rate limiting at both Nginx and the application layer.

  • Restrict access to Nginx status endpoints and internal health routes.

  • Forward only headers the application trusts, and validate Host against the configured server_name.

  • Keep TLS private keys readable only by the Nginx service account, and back up both configuration and certificates securely.

16

How does a trailing slash in Nginx proxy_pass change URI forwarding?

The trailing slash in proxy_pass determines whether NGINX forwards the request URI unchanged or replaces the matched location prefix with the path specified by proxy_pass. This behavior is called URI replacement and directly affects what path the upstream application receives.

Read full answer

Applies toNGINX 1.24+ open-source edition

Core Behavior

location proxy_pass Client request Upstream request
/api/ http://api_backend /api/users /api/users
/api/ http://api_backend/ /api/users /users
/api http://api_backend/ /api/users /users
/api http://api_backend /apifoo /apifoo
  • Without a path or trailing slash, such as proxy_pass http://api_backend;, NGINX normally forwards the original request URI.

  • With a trailing slash, such as proxy_pass http://api_backend/, the matched location prefix is replaced by /.

  • Query parameters are preserved. For example, /api/users?active=true becomes /users?active=true when the prefix is replaced.

Location Matching

The slashes in location and proxy_pass control different things:

  • location /api/ matches /api/users, but not /api or /apifoo.

  • location /api matches /api/users, /api, and /apifoo.

  • The selected location determines which proxy_pass applies.

  • The URI in that proxy_pass determines whether the selected path is preserved or replaced.

NGINX first checks for an exact match such as location = /api. It then finds the longest matching prefix. If that prefix uses ^~, it is selected without checking regex locations. Otherwise, NGINX checks regex locations in configuration order, and the first matching regex takes precedence over the prefix match.

How It Works Under the Hood

The NGINX master process parses the configuration and manages worker processes. Workers use an event-driven architecture to accept requests, select a location, construct the upstream request according to proxy_pass, and stream the upstream response back to the client.

Client-facing HTTP/2 or HTTP/3 does not change these URI rules. The rewritten path is still passed to the upstream server using the upstream protocol configured for that proxy_pass.

Code Example

Place this configuration in an NGINX http-context include such as /etc/nginx/conf.d/example.com.conf:

upstream api_backend {
    server 10.0.0.10:8080;
}

server {
    listen 80;
    server_name example.com;

    # Preserve the /api/ prefix for the upstream application.
    location /api/ {
        proxy_pass http://api_backend;

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Remove the /legacy/ prefix before forwarding.
    location /legacy/ {
        proxy_pass http://api_backend/;

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Validate and reload the configuration:

nginx -t
nginx -s reload

Expected upstream paths:

curl --resolve example.com:80:127.0.0.1 http://example.com/api/users
# Backend receives: /api/users

curl --resolve example.com:80:127.0.0.1 http://example.com/legacy/users
# Backend receives: /users

Production Considerations

  • Routing failures: A path mismatch usually produces an upstream 404, while connection, TLS, or timeout failures commonly produce 502 or 504.

  • Logging: NGINX access logs normally show the client-facing URI, not necessarily the rewritten upstream path. Correlate them with upstream application logs.

  • Headers: Review Host and X-Forwarded-* headers. Forwarded headers should only be trusted according to the network’s proxy trust boundary.

  • TLS upstreams: For HTTPS upstreams, explicitly configure certificate verification with proxy_ssl_verify on, a trusted certificate bundle, SNI, and the expected certificate name.

  • DNS and reloads: Hostnames in statically configured upstream groups are normally resolved when NGINX starts or reloads; an IP change may require a graceful reload.

  • Timeouts: Tune proxy_connect_timeout and proxy_read_timeout per route rather than using one global value for every workload.

Best Practices and Common Pitfalls

  • Define the backend’s expected path contract before choosing the proxy_pass form.

  • Test both exact and prefix routes, including requests such as /apifoo that can expose accidental prefix matching.

  • Do not treat the trailing slash as cosmetic; it changes the upstream URI.

  • In regex locations, avoid relying on proxy_pass URI rewriting because NGINX restricts URI parts in regex and named-location contexts; use an explicit rewrite rule when path transformation is required.

  • Always run nginx -t before a graceful reload and monitor 4xx, 5xx, latency, and upstream connection errors after the change.

17

Which request headers should Nginx forward to upstream servers?

For a reverse proxy, forward the public hostname and trusted client-network information using Host, X-Forwarded-For, and X-Forwarded-Proto. These headers must preserve the external request’s meaning without allowing untrusted clients to spoof the client IP or protocol.

Read full answer

Applies toNginx OSS 1.24 and later

Header Recommendations

Header Recommended value Purpose and caveat
Host $host Identifies the public virtual host expected by the application. Nginx otherwise defaults this proxy header to $proxy_host, which is the upstream group or address. Use $http_host when the original port must be preserved.
X-Forwarded-For $remote_addr at a public edge Sends the client IP seen by Nginx and removes any client-supplied chain, preventing basic spoofing. Behind a trusted proxy chain, use $proxy_add_x_forwarded_for instead.
X-Forwarded-Proto $scheme Sends the protocol used for the request received by Nginx: https when TLS terminates at Nginx and http otherwise. It is commonly used for redirects, absolute URLs, and secure-cookie decisions.

How the Values Work

  • $host: Derived from the request’s host information and normalized to lowercase, with the port removed. It may fall back to the matched server_name.

  • $http_host: The original Host header, including its port if present. If the request contains no Host header (or it is empty), it falls back to the server name, i.e. the same value as $host.

  • $remote_addr: The client address as currently observed by Nginx. The ngx_http_realip_module can change it to a trusted upstream-provided client address.

  • $proxy_add_x_forwarded_for: Appends $remote_addr to an existing X-Forwarded-For header. If no incoming header exists, the result is simply $remote_addr. It does not validate the incoming chain.

  • $scheme: Reflects the scheme of the request handled by this Nginx instance, not the scheme of Nginx’s connection to the upstream.

Nginx’s proxy module replaces the corresponding client headers with the configured proxy headers. Unconfigured headers, such as Authorization and Cookie, are still forwarded normally.

Proxy Chains and Trust Boundaries

  • Directly internet-facing Nginx: Overwrite X-Forwarded-For with $remote_addr. Otherwise, a client can submit its own X-Forwarded-For and make $proxy_add_x_forwarded_for preserve a false address.

  • Nginx behind a trusted load balancer: Use $proxy_add_x_forwarded_for only when the load balancer sanitizes the chain and Nginx is reachable exclusively from that proxy.

  • TLS terminated before Nginx: $scheme may be http even though the browser used HTTPS. In that topology, the load balancer should overwrite X-Forwarded-Proto, and Nginx must accept that value only from the trusted load balancer.

  • Application validation: The upstream application should trust forwarding headers only from known Nginx instances and determine the client IP using its trusted-proxy configuration. Reading the leftmost X-Forwarded-For value without validation is unsafe.

Production Failure Modes

  • Incorrect Host values can produce redirects to the upstream hostname, broken absolute links, or failed tenant and virtual-host routing.

  • Incorrect X-Forwarded-Proto values can cause HTTP/HTTPS redirect loops or cause applications to issue insecure cookies.

  • Incorrect X-Forwarded-For values can corrupt rate limiting, audit logs, geolocation, and abuse controls.

  • With proxy_pass http://app_backend;, the original request URI is preserved. Adding a trailing slash, such as proxy_pass http://app_backend/;, replaces the matched location prefix with /.

  • Monitor upstream status codes, latency, timeouts, and connection errors. The upstream must also be configured to trust headers only from Nginx.

Code Example

This complete configuration is suitable for an Nginx instance directly receiving client traffic. The upstream addresses are placeholders.

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    upstream app_backend {
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
        keepalive 32;
    }

    server {
        listen 8080;
        server_name example.com;

        location /api/ {
            proxy_pass http://app_backend;
            proxy_http_version 1.1;

            # Required for connection reuse to the upstream group.
            proxy_set_header Connection "";

            # Public hostname and protocol.
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-Proto $scheme;

            # Public edge: discard any client-supplied forwarding chain.
            proxy_set_header X-Forwarded-For $remote_addr;

            proxy_connect_timeout 5s;
            proxy_read_timeout 30s;
        }
    }
}

Behind a trusted, sanitizing proxy chain, replace the X-Forwarded-For line with:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Validate and apply the configuration without interrupting existing connections:

sudo nginx -t && sudo nginx -s reload

Best Practices

  • Prefer $host for normal public-host forwarding; use $http_host only when preserving an explicit port is required.

  • Overwrite client-supplied forwarding headers at the first trusted edge.

  • Restrict network access to Nginx so applications and proxies cannot be contacted directly.

  • Keep the application’s trusted-proxy list synchronized with load-balancer and network changes.

  • Test both HTTP and HTTPS requests and verify the exact headers received by the upstream.

  • Back up configuration files, validate every change before reload, and monitor reload failures and upstream error rates during rolling upgrades.

18

How does Nginx recover real client IPs behind CDNs and load balancers?

Real client IP recovery in Nginx uses the ngx_http_realip_module to replace the connecting proxy’s address with the original client address from a trusted HTTP header. Only proxies whose addresses are explicitly trusted can influence the result.

Read full answer

Applies toNginx 1.24+ Open Source with `ngx_http_realip_module`

How It Works

Nginx uses a master process to manage configuration and worker processes that handle connections through an event-driven event loop. During request processing, a worker applies the real-IP module before access controls, rate limiting, proxying, and logging.

The important variables are:

  • $remote_addr: The effective client address after the real-IP rewrite.

  • $realip_remote_addr: The original address of the peer that connected to Nginx, normally the CDN or load balancer.

  • $http_x_forwarded_for: The raw X-Forwarded-For request header.

If the direct peer is not trusted, or the configured header is missing, Nginx leaves $remote_addr unchanged.

The same behavior applies to HTTP/1.1, HTTP/2, and HTTP/3 requests because the rewrite operates at Nginx’s HTTP layer, independently of the client-facing protocol.

Trusted Headers

Header Typical use Important consideration
X-Forwarded-For CDN or load-balancer chains Usually contains multiple addresses; use recursive processing.
X-Real-IP Proxies that publish one client address Ensure the edge proxy removes any client-supplied value.
CF-Connecting-IP Cloudflare-specific forwarding Trust only Cloudflare’s published address ranges and configured ranges.

With real_ip_recursive off, Nginx uses the rightmost address in the configured header. With real_ip_recursive on, it scans the list from right to left and selects the first untrusted address. This matters for a chain such as Client -> CDN -> Load Balancer -> Nginx: if the CDN and load-balancer networks are trusted, Nginx ultimately selects the client’s address rather than an intermediate proxy’s address.

Code Example

Replace the example ranges with the actual CIDRs from which your CDN and load balancer connect to Nginx:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    log_format client_ip '$remote_addr $realip_remote_addr [$time_local] '
                       '"$request" $status $body_bytes_sent '
                       '"$http_user_agent"';

    upstream app_backend {
        server 127.0.0.1:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;

        # Load balancer or reverse-proxy egress range.
        set_real_ip_from 10.0.0.0/16;

        # Placeholder CDN egress range, skipped by the recursive scan.
        set_real_ip_from 192.0.2.0/24;

        real_ip_header X-Forwarded-For;
        real_ip_recursive on;

        location / {
            proxy_http_version 1.1;
            proxy_set_header Connection "";

            # Pass the verified client IP to the application.
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;

            proxy_pass http://app_backend;
        }
    }
}

Validate the configuration before reloading the running instance:

sudo nginx -t && sudo nginx -s reload

The reload is graceful: the master starts workers with the new configuration while existing workers finish active requests.

Production Troubleshooting

  • Verify the header at every hop: Confirm what the CDN sends to the load balancer and what the load balancer sends to Nginx. Some proxies append to X-Forwarded-For, while others replace it.

  • Inspect all three variables: Logging $remote_addr, $realip_remote_addr, and $http_x_forwarded_for immediately reveals whether the rewrite occurred and what data arrived.

  • Check the direct peer: Nginx must trust the network address of the proxy that opens the connection. Trusting only the CDN is insufficient when the load balancer is the direct peer.

  • Account for address changes: Cloud/CDN egress ranges can expand or change. Automate updates and monitor when requests suddenly appear to originate from a proxy address.

  • Use the effective address consistently: Rate-limit zones based on $binary_remote_addr will group requests by the rewritten client address, provided the real-IP module is active.

Security and Best Practices

  • Trust only known proxies: Never use set_real_ip_from 0.0.0.0/0; or trust the entire internet. Otherwise, clients can forge forwarding headers and bypass IP-based controls.

  • Sanitize headers at the edge: The first trusted proxy should remove incoming X-Forwarded-For, X-Real-IP, or vendor-specific client-IP headers and write its own verified value.

  • Avoid duplicate or ambiguous headers: Configure one authoritative header in Nginx. If the application also consumes these headers, ensure it trusts the same proxy chain and uses the same extraction rules.

  • Treat client IPs as sensitive data: They may be personal data. Apply appropriate log retention, access controls, and masking policies.

  • Test before every production change: Run nginx -t, reload gracefully, and confirm the logged effective address before relying on the value for rate limiting, allowlists, or audit trails.

19

Which load balancing methods does Nginx support?

Nginx open source supports five upstream load-balancing methods: round robin, least connections, IP hash, generic hash, and random. The selected method determines which server in an upstream group receives each proxied request.

Read full answer

Applies toNginx 1.24+ open source and Nginx Plus based on Nginx 1.24+

Open-Source Methods

Method Configuration Selection behavior Typical use
Round robin Default; no directive required Selects servers sequentially. weight changes each server’s share. General-purpose balancing
Least connections least_conn Selects the server with the fewest active connections, taking weights into account. Uneven request durations or long-running requests
IP hash ip_hash Maps the client address to a backend, providing source-IP affinity. Sticky sessions when application cookies are undesirable
Generic hash hash $key Selects a backend from a chosen variable, such as $request_uri. Cache affinity or key-based routing
Random random Selects a backend randomly. Large pools or simple probabilistic distribution

Only one balancing method should be configured for an upstream. ip_hash ignores server weights; use hash when weighted, key-based selection is required.

Nginx Plus and Failure Handling

Nginx Plus adds the least_time method, which selects a server using upstream response-time information. It also supports active health checks, whereas open-source Nginx supports only passive failure handling.

In open-source Nginx, max_fails and fail_timeout determine when a repeatedly failing peer is temporarily excluded. Their defaults are one failed attempt and a 10-second failure window, respectively. proxy_next_upstream can also retry a failed request against another peer.

Least connections uses the number of active connections, not measured latency. Long-lived requests can therefore distort its decisions even when it balances ordinary traffic well.

Nginx Architecture and Configuration Context

The Nginx master process reads the configuration and manages worker processes. Workers use an event-driven architecture and independently select upstream peers, so short-term traffic can be uneven between workers. A graceful reload starts new workers with the new configuration while existing workers drain their current connections.

The http context contains upstream groups, server blocks, and location blocks. server selects a virtual host, while location selects request handling by URI. Nginx checks an exact = match first, then the longest prefix match using ^~, then regular-expression locations in configuration order, and finally the longest ordinary prefix match.

Static files handled through root, alias, or try_files do not consume an upstream peer. TLS termination, HTTP/2, and HTTP/3 are independent of the balancing method. HTTP/3 also requires compatible client support and an Nginx build with QUIC support; open-source Nginx added it in 1.25.0 as an experimental feature.

Production Operations

  • Monitoring: Log $upstream_addr, $upstream_status, $upstream_response_time, and $upstream_connect_time. Alert on sustained 502/504 responses, latency, retries, and uneven peer utilization.

  • Retries: Restrict proxy_next_upstream retries for non-idempotent operations unless the application explicitly supports them.

  • Connection reuse: Upstream keepalive reduces handshake overhead, but worker-local connections can make observed short-term distribution less even.

  • Security: Use TLS to untrusted networks, sanitize externally supplied forwarding headers, rate-limit abusive clients with limit_req, and set security headers such as HSTS and CSP where appropriate.

  • Caching and compression: proxy_cache and gzip are orthogonal to peer selection. Caching reduces backend load, while compression affects response size and CPU usage.

  • Upgrades: Back up the configuration, validate it before reload, use graceful reloads, and monitor error rates and latency during the transition.

Common Mistakes

  • Balancing directives belong inside upstream, not inside server or location.

  • ip_hash can create hotspots for clients behind NAT or proxies, especially because IPv4 selection uses the first three address octets.

  • The trailing slash in proxy_pass changes URI forwarding. With location /api/ and proxy_pass http://backend, /api/orders remains unchanged; with proxy_pass http://backend/, the /api/ prefix is replaced and the request becomes /orders.

  • If one backend receives little traffic, inspect the selected method, weights, passive failure state, retries, and per-worker distribution before assuming the method itself is defective.

20

How does open-source Nginx detect unhealthy upstream servers?

In open-source Nginx, upstream health checking is passive: Nginx learns about backend health from failures encountered while proxying real requests. It can fail over to another upstream and temporarily exclude a failed peer, but it does not continuously probe every backend.

Read full answer

Applies toopen-source NGINX 1.24+ (1.x)

How Passive Health Checking Works

  • The Nginx master process creates worker processes that accept connections and use an event-driven loop to proxy requests.

  • When an upstream attempt encounters an eligible error or timeout, Nginx can select another server from the upstream block.

  • max_fails and fail_timeout control temporary peer exclusion after repeated unsuccessful attempts.

  • By default, passive failure state is local to each worker, so workers can temporarily disagree about a backend’s health. An upstream zone can share runtime state between workers, reducing this inconsistency.

  • A backend receiving no requests may remain in rotation because Nginx has no failure to observe.

  • NGINX Plus supports proactive health_check probes; stock open-source Nginx does not. Third-party modules can provide active probes, but they are not part of upstream Nginx.

Key Directives

Directive Behavior
max_fails Maximum unsuccessful attempts during fail_timeout before a peer is temporarily skipped. The default is 1; 0 disables failure accounting.
fail_timeout Period used to count failures and the duration for which an excluded peer is avoided. The default is 10s.
proxy_next_upstream Determines whether a failed request is retried on another peer. The default is error timeout; selected HTTP statuses such as http_502, http_503, and http_504 can also be included.
proxy_next_upstream_tries Limits total upstream attempts, including the initial attempt. The default is 0, which removes the limit.
proxy_next_upstream_timeout Limits the time allowed for upstream failover processing. The default is 0, which removes the limit.

An HTTP 502, 503, or 504 can trigger a retry when listed in proxy_next_upstream, but the response status itself is not an unsuccessful connection attempt and therefore does not by itself increment the passive failure count.

Production Monitoring and Operations

Monitor per-request upstream behavior rather than expecting a persistent “healthy” status:

  • Log $upstream_addr, $upstream_status, $upstream_connect_time, $upstream_header_time, $upstream_response_time, and $request_time.

  • Alert on upstream error rates, retry amplification, connection failures, and latency.

  • Keep timeouts layered so proxy_connect_timeout, proxy_read_timeout, and proxy_next_upstream_timeout cannot produce excessive retry storms.

  • Keep configuration under version control, maintain a rollback copy, and validate changes with sudo nginx -t before a graceful reload.

  • Roll nodes one at a time during production changes. Passive observations are not transferred between old and new workers merely because of a graceful reload.

Failure Modes and Security

  • Retrying after a lost response can duplicate side effects if the upstream already processed the request. Avoid the non_idempotent option unless the application provides suitable idempotency controls.

  • TLS handshake and certificate failures can appear as upstream errors. Keep upstream certificate verification enabled and configure trusted certificates correctly.

  • Client-facing HTTP/2 or HTTP/3 does not change backend health semantics; native HTTP/3 support begins with NGINX 1.25 and still requires a build with the appropriate QUIC support.

  • Static-file serving, caching, compression, rate limiting, and security headers operate at the edge and do not make upstream checking proactive.

  • For active checks, use NGINX Plus or an external load balancer that can remove unhealthy targets before requests reach them.

Common Mistakes

  • Expecting open-source Nginx to remove an idle, broken backend without a failed request.

  • Setting max_fails without understanding that it tracks unsuccessful connection attempts and timeouts, not ordinary HTTP status responses.

  • Making failover thresholds too aggressive, causing a brief backend hiccup to exclude a healthy peer.

  • Confusing routing with health checking: proxy_pass http://app_backend; preserves the request URI, while proxy_pass http://app_backend/; replaces the matched location prefix with /.

21

What are max_fails and fail_timeout in Nginx?

max_fails and fail_timeout are passive health-check parameters on an upstream server. They control how many communication failures occur within a time window before Nginx marks that backend unavailable, and how long it stays out of rotation.

Read full answer

Applies toNginx 1.24+ (open source) upstream passive health checks.

How They Work

  • max_fails: number of unsuccessful attempts to communicate with a backend during fail_timeout. The default is 1. Setting it to 0 disables failure accounting.

  • fail_timeout: the time window in which max_fails failures must occur, and also the period for which the backend is considered unavailable after being marked down. The default is 10s.

When a backend reaches max_fails failures within fail_timeout, Nginx stops sending new requests to it for another fail_timeout interval. After that, it is tried again.

What Counts as a Failure

Failures are communication problems such as connection errors and timeouts. Request retry behavior is also influenced by proxy_next_upstream, which defines when Nginx may send a request to another backend.

Comparison

Parameter Meaning Default Common Tuning
max_fails Failures needed to mark backend down 1 2 or 3 to avoid flapping
fail_timeout Failure window and downtime duration 10s 30s or 60s for unstable networks

Code Example

upstream backend {
    server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.12:8080 backup;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout http_502 http_503 http_504;
    }
}

Production Notes

  • The defaults are aggressive: one timeout can remove a backend for 10 seconds.

  • Passive checks only react to real traffic; they do not proactively probe idle backends.

  • Open-source Nginx does not provide active health checks; Nginx Plus adds health_check.

  • Monitor $upstream_status, $upstream_addr, and $upstream_response_time in access logs, and alert on repeated 502/503/504 responses.

  • Use backup servers for fallback capacity, but test failover regularly.

Common Pitfalls

  • Setting max_fails=0 disables failure detection entirely.

  • A very short fail_timeout can cause rapid flapping during brief latency spikes.

  • Expecting HTTP 5xx responses alone to mark a backend down without considering proxy_next_upstream.

22

How do you configure sticky sessions in Nginx?

Sticky sessions keep requests from the same client on one upstream server. Nginx OSS supports IP-based affinity with ip_hash and deterministic cookie-based routing with hash; the built-in sticky cookie directive requires NGINX Plus.

Read full answer

Applies toNginx OSS 1.24+; NGINX Plus R33+

Choosing a Sticky Mechanism

Mechanism Available in Behavior Main limitation
ip_hash Nginx OSS Routes clients by IP address Large NAT groups can overload one server
hash ... consistent Nginx OSS Routes by a cookie or other request key Backend must issue the session cookie
sticky cookie NGINX Plus Nginx issues and validates an affinity cookie Commercial feature
Third-party sticky module Community module Adds cookie-based affinity Requires external maintenance and trust

For internet-facing applications, cookie-based affinity is usually preferable because it works correctly when multiple users share an IP address. Shared session storage such as Redis remains preferable when losing or moving a session would be unacceptable.

How It Works

  • ip_hash: Calculates affinity from the client address. It uses the first three IPv4 octets or the entire IPv6 address, so clients behind the same NAT may collide.

  • hash $sticky_key consistent: Uses consistent hashing to map a key to an upstream peer. The key can come from an application cookie such as SESSIONID.

  • NGINX Plus sticky cookie: Tracks the selected peer and returns an affinity cookie to the client.

Upstream selection occurs inside each Nginx worker process. A graceful reload creates new workers with the updated configuration while existing workers finish their current requests.

Code Example

For Nginx OSS, place the following inside the existing http {} context. The application must create a SESSIONID cookie on its response; Nginx then uses that value for subsequent requests.

# Requests without a session cookie use a random request ID, avoiding
# concentration on one server before the application creates the cookie.
map $cookie_SESSIONID $sticky_key {
    ""      $request_id;
    default $cookie_SESSIONID;
}

upstream app_backend {
    hash $sticky_key consistent;

    server 10.0.0.11:8080;
    server 10.0.0.12:8080;

    keepalive 32;
}

log_format upstream
    '$remote_addr "$request" upstream=$upstream_addr '
    'status=$upstream_status request_time=$request_time';

server {
    listen 80;
    server_name app.example.com;

    access_log /var/log/nginx/upstream.access.log upstream;

    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;

        proxy_set_header Host $host;
        proxy_set_header Connection "";
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Retry idempotent requests when the selected peer is unavailable.
        proxy_next_upstream error timeout http_502 http_503 http_504;
    }
}

Validate and apply the configuration:

sudo nginx -t && sudo nginx -s reload

For NGINX Plus, replace the upstream configuration with the following. It does not require the application to create an affinity cookie:

upstream app_backend {
    zone app_backend 64k;

    server 10.0.0.11:8080;
    server 10.0.0.12:8080;

    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

Operational Considerations

  • Health and failover: Configure health checks and verify behavior when a backend is removed. A failed request may be retried on another peer, where local session state is unavailable.

  • Monitoring: Log $upstream_addr and $upstream_status, and alert on uneven connection counts, elevated upstream errors, and unhealthy peers.

  • Session durability: Use a shared session store when failover must preserve sessions. Sticky routing reduces dependence on shared storage but does not eliminate it.

  • Capacity: Sticky traffic can create hot servers. Load-test realistic cookie distributions and monitor per-peer CPU, memory, latency, and active connections.

  • Upgrades: Drain or gracefully reload workers, verify backend capacity, and keep the previous configuration available for rollback.

Common Pitfalls

  • Trusting client headers incorrectly: If ip_hash is used behind a load balancer, restore the real client address with the ngx_http_realip_module. Configure set_real_ip_from only for trusted proxy addresses and prevent direct access from untrusted networks.

  • Assuming stickiness guarantees session survival: A backend failure or deployment can move a request to a server without the corresponding session.

  • Ignoring cookies before login: If every request has an empty cookie value, a deterministic configuration may send all users to one server. Use a random fallback, as shown above.

  • Testing only HTTP: Production affinity cookies should normally carry Secure and appropriate SameSite attributes and be used over HTTPS.

  • Adding unsafe retries: Avoid non_idempotent unless duplicate POST requests are acceptable.

23

How do you enable keepalive connections to upstreams in Nginx?

Keepalive connections to upstreams in Nginx are enabled by combining the keepalive directive inside an upstream block with HTTP/1.1 and a cleared Connection header on the proxy side. Without all three, Nginx defaults to HTTP/1.0 with Connection: close and opens a new TCP connection per request.

Read full answer

Applies toNginx 1.24+ (open source) and Nginx Plus; behaviour identical for HTTP upstreams.

How It Works

By default, proxy_pass speaks HTTP/1.0 to backends and sends Connection: close, so every request pays a TCP (and possibly TLS) handshake. To reuse connections:

  • keepalive N; in the upstream block tells each worker to cache up to N idle connections to that upstream group.

  • proxy_http_version 1.1; switches the upstream protocol to HTTP/1.1.

  • proxy_set_header Connection ""; removes the Connection: close header so the backend keeps the socket open.

Connections are cached per worker process, not globally. With 8 workers and keepalive 32, you can hold up to 256 idle sockets to a backend.

Key Directives

  • keepalive — number of idle connections cached per worker. Set it to roughly the expected concurrency per worker, not total traffic.

  • keepalive_requests (default 1000) — max requests per reused connection before it is closed. Lower it if backends leak memory per connection.

  • keepalive_timeout (default 60s) — how long an idle cached connection stays open.

  • keepalive_time (1.19.10+) — hard maximum lifetime of a connection regardless of activity; useful for rotating backends behind DNS.

Common Pitfalls

  • Setting keepalive alone does nothing — the missing proxy_http_version 1.1 and Connection "" are the #1 cause of “keepalive not working” tickets.

  • keepalive is ignored for ip_hash and least_conn? No — it works with all balancing methods, but sticky/hash with $remote_addr still benefits.

  • Backends must actually support keepalive and not send Connection: close. Some frameworks (old PHP-FPM via FastCGI, gunicorn with --keep-alive 0) close anyway.

  • Cached connections count against backend max_connections / file descriptors; size backend pools accordingly.

  • DNS-based upstreams: cached connections pin to the resolved IP until keepalive_timeout expires; use keepalive_time plus resolver with valid= for rotation.

Monitoring and Operations

  • nginx -t validates syntax; curl -s http://127.0.0.1/nginx_status (with stub_status) shows active connections.

  • Watch backend connection counts and TIME_WAIT on the Nginx host; a drop after enabling keepalive confirms reuse.

  • During deploys, graceful reload (nginx -s reload) keeps workers draining old connections; cached idle sockets close with the old worker.

  • If a backend restarts, Nginx detects the closed socket on next use and retries (once, by default) on another connection.

Code Example

upstream api_backend {
    server 10.0.0.10:8080;
    server 10.0.0.11:8080;

    keepalive 32;          # idle connections cached per worker
    keepalive_requests 1000;
    keepalive_timeout 60s;
    keepalive_time 1h;
}

server {
    listen 443 ssl;
    server_name api.example.com;

    location / {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Best Practices

  • Size keepalive to concurrency_per_worker * 1.2, not total QPS; oversized values waste backend FDs.

  • Always pair with proxy_http_version 1.1 and proxy_set_header Connection "".

  • Set keepalive_time when backends are behind autoscaling or DNS rotation.

  • Verify with backend metrics (connection count) and ss -tn state established on the Nginx host before and after.

  • For gRPC/HTTP/2 upstreams, use grpc_pass with grpc_set_header equivalents and HTTP/2 keepalive is implicit.

24

How to enable HTTPS with TLS in Nginx?

To serve HTTPS in Nginx, you terminate TLS in a listen 443 ssl server block using ssl_certificate (full chain) and ssl_certificate_key (private key), then redirect plain HTTP to HTTPS. Nginx’s worker processes perform the TLS handshake via OpenSSL and serve or proxy content over the encrypted connection.

Read full answer

Applies toNginx 1.24+ on Linux (OpenSSL 3.x)

How TLS Termination Works

  • The master process reads configuration; worker processes handle connections through the event loop, so TLS handshakes scale across workers.

  • ssl_certificate must contain the leaf certificate followed by intermediate certificates; browsers fail to build the chain if intermediates are missing.

  • The private key must be readable by the Nginx worker user (usually www-data or nginx) and protected with mode 600 or 640.

  • Server Name Indication (SNI) lets one IP serve multiple certificates; Nginx selects the matching server_name block automatically.

Minimal Working Configuration

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate     /etc/nginx/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

    location / {
        root /var/www/example.com;
        index index.html;
    }
}

Key Directives Explained

  • listen 443 ssl http2 enables TLS and HTTP/2 on the same port (Nginx 1.24 syntax).

  • ssl_protocols disables legacy TLS 1.0/1.1; keep only TLS 1.2 and 1.3.

  • ssl_session_cache shared:SSL:10m allows session resumption across workers, reducing handshake cost.

  • ssl_session_tickets off avoids ticket key rotation complexity; rely on session cache instead.

  • Strict-Transport-Security (HSTS) tells browsers to always use HTTPS; only enable after confirming HTTPS works.

Operational Commands

sudo nginx -t                    # validate config before reload
sudo systemctl reload nginx      # graceful reload, no dropped connections
openssl x509 -in fullchain.pem -noout -subject -dates -issuer

Common Pitfalls

  • Serving only the leaf certificate without intermediates causes “unable to verify” errors on some clients.

  • Forgetting to reload after renewal leaves the old certificate in memory until restart.

  • Setting ssl_certificate to a path the worker cannot read produces a permission error at reload.

  • Enabling HSTS before HTTPS is fully working can lock users out of the site.

Best Practices

  • Automate renewal with Let’s Encrypt (certbot or acme.sh) and reload Nginx on renewal via a deploy hook.

  • Store certificates outside the web root and back them up with the private key.

  • Test the result with curl -I https://example.com and an external scanner such as SSL Labs.

  • Keep ssl_session_tickets off unless you implement secure ticket key rotation.

25

How to obtain Let's Encrypt certificates with Certbot?

Certbot automates requesting, installing, and renewing free Let’s Encrypt TLS certificates, and it can configure Nginx for you or just drop certificates on disk for you to wire up manually.

Read full answer

Applies toCertbot 2.x with Nginx 1.24+ on Linux (Ubuntu 22.04/24.04, RHEL 9)

How It Works

Certbot talks to the Let’s Encrypt ACME server, proves you control the domain (usually via HTTP-01 challenge served on port 80), downloads the certificate chain, and stores it under /etc/letsencrypt/live/<domain>/. It then either edits your Nginx config (with the nginx plugin) or leaves files for you to reference. A systemd timer renews certificates before expiry.

Installation

Install Certbot and the Nginx plugin from your distro or the official snap. On Ubuntu:

sudo apt update
sudo apt install certbot python3-certbot-nginx

Ensure Nginx is running and a server block already answers on port 80 for the domain, otherwise the HTTP-01 challenge fails.

Obtaining and Installing a Certificate

The simplest path uses the Nginx plugin, which edits config and reloads Nginx:

sudo certbot --nginx -d example.com -d www.example.com

Certbot will prompt for an email and agreement to terms; add --non-interactive --agree-tos -m admin@example.com for automation. It creates the certificate and updates the server block with ssl_certificate and ssl_certificate_key.

If you prefer manual control, use webroot mode so Nginx keeps serving traffic:

sudo certbot certonly --webroot -w /var/www/example.com -d example.com

Then reference the files yourself:

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # ... locations ...
}

Always use fullchain.pem, not cert.pem, so clients receive the intermediate.

Renewal

Certificates last 90 days. Certbot installs a systemd timer (certbot.timer) that runs certbot renew twice daily and renews anything within 30 days of expiry. Test it without changing anything:

sudo certbot renew --dry-run

For Nginx, renewal reloads the server automatically when using the plugin. With manual config, add a deploy hook:

sudo certbot renew --deploy-hook "systemctl reload nginx"

Or persist it in /etc/letsencrypt/renewal/example.com.conf under renew_hook.

DNS-01 and Wildcards

HTTP-01 cannot issue wildcard certificates. For *.example.com, use DNS-01 with a provider plugin, e.g.:

sudo certbot certonly --dns-cloudflare \
  --dns-cloudflare-credentials /etc/letsencrypt/cloudflare.ini \
  -d example.com -d '*.example.com'

Keep credential files chmod 600 and owned by root.

Common Pitfalls and Operations

  • Port 80 must be reachable from the internet for HTTP-01; firewalls or missing server_name matches cause “Connection refused” failures.

  • IPv6: ensure listen [::]:80 is present if the domain has AAAA records, or validation fails on IPv6.

  • Rate limits: Let’s Encrypt allows 5 duplicate certificates per week per domain; use --dry-run against staging (--server https://acme-staging-v02.api.letsencrypt.org/directory) while testing.

  • Permissions: /etc/letsencrypt is root-only; Nginx reads certs as root before dropping privileges, which is fine, but never chmod keys world-readable.

  • Monitoring: alert on certificate expiry (e.g. ssl_cert_not_after in Prometheus) and on certbot renew failures in journald: journalctl -u certbot.service.

  • Upgrades: prefer the snap or distro package; avoid mixing pip installs with system packages.

Best Practices

  • Automate renewal and verify with --dry-run after any config change.

  • Use a single certificate covering all needed names rather than many overlapping certs.

  • Apply modern TLS settings in Nginx alongside the new cert. Let’s Encrypt shut down its OCSP service in 2025, so OCSP stapling no longer applies to its certificates.

  • Back up /etc/letsencrypt (including archive/ and renewal/) as part of disaster recovery.

26

How do you redirect HTTP traffic to HTTPS with Nginx?

Use Nginx’s return directive in the HTTP server block to send a permanent redirect to the corresponding HTTPS URL. The redirect is handled by an Nginx worker during the rewrite phase and does not require communication with an upstream application.

Read full answer

Applies toNginx 1.24+ on Linux

How It Works

Nginx uses a master process to read the configuration and manage worker processes. Workers use an event-driven architecture to accept and process connections concurrently.

For a request to port 80, a server-level directive such as:

return 301 https://example.com$request_uri;

immediately produces an HTTP 301 Moved Permanently response with a Location header. Because this is a server-level return, it applies to every URI under that server block, including paths and query strings.

  • $request_uri preserves the original path and query string.

  • A fixed canonical hostname such as example.com avoids trusting arbitrary Host headers.

  • The backend application is not involved in generating the redirect.

Choosing a Redirect Status Code

Status Browser behavior Appropriate use
301 Permanent; commonly cached and may change POST to GET Most HTTP-to-HTTPS migrations
302 Temporary; usually not permanently cached Testing a migration
307 Temporary; preserves HTTP method and body Temporary redirect where method preservation matters
308 Permanent; preserves HTTP method and body Permanent API redirects requiring the original method

For normal website traffic, 301 is the conventional choice. Because browsers can cache it indefinitely, use 302 temporarily if the destination or redirect policy may change.

Production Design

  • Keep the HTTP and HTTPS configurations in the same Nginx configuration, but in separate server blocks.

  • Provision a valid certificate before sending users to the HTTPS endpoint.

  • If the site uses a reverse proxy, the redirect remains in the public-facing HTTP server; proxy_pass is used only by the HTTPS server to forward requests to the application.

  • If a load balancer terminates TLS, perform the redirect at the load balancer or pass a trusted X-Forwarded-Proto header to Nginx.

  • Do not use proxy_redirect for this purpose; it rewrites Location headers returned by an upstream, rather than creating the initial client-facing redirect.

  • HTTP/2 and HTTP/3 are negotiated after TLS. HTTP/3 uses QUIC over UDP and normally does not need a plaintext HTTP redirect.

Code Example

After a certificate has been provisioned at the indicated paths, the following configuration is valid for Nginx 1.24+:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    # Preserve the original path and query string.
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Validate and activate the configuration:

sudo nginx -t
sudo systemctl reload nginx

Verify the redirect and preservation of the query string:

curl -sS -o /dev/null -D - 'http://example.com/path?source=test'

The response should include:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/path?source=test

Failure Modes and Operations

  • Redirect loops: A proxy may forward the original scheme incorrectly, causing Nginx to redirect an HTTPS request back to HTTPS. Only trust X-Forwarded-Proto from known proxies, or perform TLS termination and redirection at the same layer.

  • Broken HTTPS endpoint: Certificate expiry, an incorrect certificate name, or a missing certificate can make the redirect appear successful while the destination fails.

  • Stale cached redirects: Browsers may retain an old 301. Temporarily use 302 if a redirect target must be changed without waiting for cache expiration.

  • ACME challenges: If an HTTP-01 certificate challenge must remain accessible, place it in a more specific location such as /.well-known/acme-challenge/ and move the redirect into location /.

  • Monitoring: Track redirect counts, 4xx/5xx rates, certificate-expiry alerts, and Nginx error logs. The default access log records the resulting 301 status.

Security and Best Practices

Use a hardcoded canonical HTTPS origin instead of dynamically redirecting to an unvalidated Host value. Confirm that every relevant hostname has HTTPS coverage before enabling HSTS with a directive such as add_header Strict-Transport-Security "max-age=31536000" always;. Avoid including includeSubDomains until every subdomain supports HTTPS, and use certificate-renewal monitoring or deployment hooks so Nginx reloads with renewed credentials.

28

What is HSTS and how do you enable it in Nginx?

HTTP Strict Transport Security (HSTS) instructs browsers to communicate with a host only over HTTPS for a specified period. Nginx enables it by returning a Strict-Transport-Security response header from HTTPS endpoints.

Read full answer

Applies toNginx 1.24+ and HSTS as defined by RFC 6797

How It Works

When a browser receives the HSTS header over a valid HTTPS response, it records the policy for the host. Subsequent HTTP requests are rewritten to HTTPS before leaving the browser.

A typical policy looks like:

Strict-Transport-Security: max-age=31536000; includeSubDomains
  • max-age=31536000: Keeps the policy active for one year.

  • includeSubDomains: Applies the policy to the domain and all existing or future subdomains.

  • preload: Indicates that the domain intends to be submitted to browser preload lists.

HSTS does not itself enable HTTPS. It also cannot protect a user’s first request, clients that ignore HSTS, or requests to unrelated domains.

Policy Options and Trade-offs

Policy Effect Operational consideration
max-age only Protects the exact host Safest starting point
includeSubDomains Protects all subdomains Every subdomain must support HTTPS permanently
preload Signals preload-list intent The domain must still be submitted separately

Start with a short max-age, confirm that HTTPS works reliably across all relevant endpoints, and then increase it. A year-long policy is commonly used for mature production domains.

If the domain uses cookies, ensure sensitive cookies also have the Secure attribute. HSTS does not automatically protect cookies on non-HTTPS requests made before the policy becomes active.

Code Example

Place the following in an http-included file such as /etc/nginx/conf.d/example.com.conf. The certificate files must exist and cover every hostname listed.

upstream app_backend {
    server 10.0.0.10:8080;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    # Permanently redirect plaintext HTTP to HTTPS.
    return 308 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    # Prevent an upstream application from sending a conflicting policy.
    proxy_hide_header Strict-Transport-Security;

    # Send HSTS on successful and error responses.
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
    }
}

Validate and activate the configuration:

sudo nginx -t
sudo systemctl reload nginx

Verify the response:

curl -sS -D - -o /dev/null https://example.com/

The response should contain:

Strict-Transport-Security: max-age=31536000; includeSubDomains

Common Failure Modes

  • Missing header on errors: Without always, Nginx may omit add_header for selected error responses.

  • Overridden inheritance: A location containing its own add_header directives stops inheriting server-level add_header directives.

  • Duplicate policies: An upstream service may already emit HSTS. proxy_hide_header lets the edge application own the policy.

  • Broken subdomains: includeSubDomains can cause failures if any subdomain has invalid certificates or cannot serve HTTPS.

  • TLS termination elsewhere: If a load balancer terminates TLS, configure HSTS at the edge that browsers contact, or ensure the proxy preserves the intended header consistently.

  • Redirect loops: Check X-Forwarded-Proto, the public HTTPS listener, and application URL-generation logic when HTTPS requests become HTTP internally.

Production Best Practices

Monitor certificate expiry, TLS negotiation failures, redirect loops, and unexpected HSTS headers across every externally reachable hostname. Test changes in staging, but remember that browsers cache HSTS independently of your staging environment.

The preload token does not automatically submit a domain. Preloading requires meeting the current browser preload requirements and submitting the registrable domain through the browser vendor’s process. Because preload removal is not immediate, use it only after confirming that every subdomain is permanently HTTPS-capable.

29

What is OCSP stapling in Nginx?

OCSP stapling is a TLS extension in which Nginx obtains a signed OCSP response for its leaf certificate and includes that response in the TLS handshake. Clients can then verify the certificate’s revocation status without each client making a separate OCSP request, reducing handshake latency and avoiding disclosure of the client’s IP address to the issuer through the OCSP exchange. The responder still sees the Nginx server’s own address when Nginx fetches the response.

Read full answer

Applies toNginx OSS 1.24+

How It Works

  1. The server certificate normally contains an OCSP responder URL in its Authority Information Access extension. Nginx can instead use the URL specified by ssl_stapling_responder.

  2. Nginx asks the issuer’s authorized OCSP responder for the leaf certificate’s status lazily, when a TLS handshake first needs it, not at startup; the first clients after a start or reload may therefore receive no staple.

  3. With ssl_stapling_verify on, Nginx verifies the response’s signature and its relationship to the trusted issuer chain. The response may be signed by the CA itself or by a delegated responder it authorized.

  4. Nginx caches the response, manages its refresh before expiry, and supplies it to clients through the TLS certificate-status extension.

  5. A client receives the signed status during the handshake instead of making a separate OCSP request. Clients remain free to ignore the stapled response and apply their own revocation policy.

Stapling is a TLS feature rather than an HTTP feature, so it is not tied to HTTP/1.1 and can be used with HTTP/2 and HTTP/3 when the deployed TLS stack supports the certificate-status exchange. It applies only to Nginx’s client-facing TLS connection; a separate TLS connection to a reverse-proxy upstream does not automatically inherit the downstream staple.

Configuration Requirements

  • OCSP support: The certificate issuer must publish an OCSP service and authorize the responder that signs responses. Some CAs no longer do; Let’s Encrypt ended OCSP in 2025, so stapling has nothing to fetch for its certificates.

  • Certificate chain: ssl_certificate should contain the leaf certificate followed by the required intermediate certificates.

  • Enablement and verification: ssl_stapling is off by default. Enable it explicitly, and use ssl_stapling_verify on to accept an OCSP response only when its signature and trust chain validate.

  • Trusted certificates: ssl_trusted_certificate points to a PEM trust store containing the certificates needed to verify OCSP responses. It does not replace the intermediate chain in ssl_certificate.

  • Responder address: Nginx uses the URL from the certificate’s Authority Information Access extension by default. ssl_stapling_responder overrides that address.

  • DNS resolution: A usable resolver is required when the responder hostname is resolved by Nginx.

  • Network access: The Nginx host must be able to reach the OCSP responder over the transport required by that responder.

  • Accurate time: OCSP validation depends on correct system time, normally maintained through NTP.

Client OCSP Versus Server Stapling

Property OCSP stapling Client-side OCSP
Entity contacting the responder Nginx Each client or browser
Client privacy The client’s IP is not disclosed in the OCSP exchange The responder can observe the client’s IP address
Handshake latency A cached status can be included immediately May require an additional network round trip
Responder outage impact Nginx may continue serving a valid cached response until it expires Clients may be unable to obtain fresh status
Nginx responsibility Obtain, validate, refresh, and distribute the response None

Stapling does not prove that a certificate is safe. Revocation information can be delayed, and some clients treat an OCSP failure as soft-fail or use another revocation mechanism such as CRLs.

Operational Best Practices and Failure Modes

  • Monitor refresh failures: Track Nginx error logs for resolver, connection, signature-verification, and refresh errors. A successful configuration test does not guarantee that fresh OCSP data will remain available.

  • Probe externally: Periodically perform a TLS handshake from outside the serving network and verify that clients receive the expected status response.

  • Restrict egress: Permit only the required DNS and OCSP-responder traffic where practical, reducing exposure after a host compromise.

  • Handle renewal atomically: Replace the certificate and key as one deployment, validate the configuration, and reload Nginx so workers load the new material and refresh its revocation status.

  • Plan for responder failure: If Nginx cannot obtain or validate a response, it continues serving TLS and stops sending the staple once the cached response expires. Client behavior then depends on its revocation and soft-fail policy.

  • Do not treat stapling as certificate monitoring: Continue monitoring certificate expiry, deployment correctness, TLS handshake errors, and revocation procedures independently.

30

How do I configure Nginx for HTTP/2 and HTTP/3?

HTTP/2 and HTTP/3 use different transports: HTTP/2 normally uses TLS/TCP, while HTTP/3 uses QUIC/UDP and requires TLS 1.3. Native HTTP/3 support requires Nginx OSS 1.25.0+, while the combined configuration using the modern http2 on; directive requires 1.25.1+.

Read full answer

Applies toNginx OSS 1.27.2+ (HTTP/3 stable), Nginx OSS 1.25.1–1.27.1 (same syntax, but HTTP/3 experimental), and Nginx OSS 1.24 (HTTP/2 only)

How It Works

Protocol Transport TLS Nginx OSS support
HTTP/2 TCP, normally port 443 TLS 1.2 or TLS 1.3 for HTTPS Available since 1.9.5; examples here target 1.24+
HTTP/2 cleartext (h2c) TCP without TLS None Available in Nginx 1.24+
HTTP/3 QUIC over UDP, normally UDP 443 TLS 1.3 mandatory Introduced in 1.25.0; stable since 1.27.2

Over TLS, HTTP/2 is negotiated through the TLS ALPN extension. HTTP/3 uses QUIC, which has its own encrypted handshake and supports connection migration. The same certificate and private key can serve both protocols, but separate TCP and UDP listeners are required.

HTTP/3 was experimental in Nginx 1.25.0–1.27.1 and became stable in 1.27.2. Use a supported stable release for production deployments.

Code Example

After provisioning the certificate and key at the shown paths, the following is a complete main configuration enabling HTTP/1.1, HTTP/2, and HTTP/3:

events {
    worker_connections 1024;
}

http {
    upstream app_backend {
        least_conn;
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
    }

    server {
        listen 443 ssl;
        listen 443 quic reuseport;

        http2 on;
        http3 on;

        server_name example.com;

        ssl_certificate     /etc/nginx/certs/example.com/fullchain.pem;
        ssl_certificate_key /etc/nginx/certs/example.com/privkey.pem;

        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 1d;

        location / {
            proxy_pass http://app_backend;

            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;
        }
    }
}

Important details:

  • listen 443 ssl; opens the TCP listener; with http2 on;, that virtual server also supports HTTP/2.

  • listen 443 quic reuseport; opens the UDP listener for QUIC and HTTP/3.

  • reuseport creates per-worker listening sockets using SO_REUSEPORT on supported operating systems and is recommended for QUIC deployments.

  • http3 on; enables HTTP/3 for the virtual server.

  • proxy_pass http://app_backend; passes the original request URI unchanged because the upstream name has no URI or trailing slash.

For Nginx 1.24, remove the HTTP/3 listener and http3 on;, then use the older HTTP/2 parameter:

listen 443 ssl http2;

That syntax remains accepted for compatibility, but http2 on; is preferred from Nginx 1.25.1 onward.

Validation and Rollout

Validate and reload the configuration:

sudo nginx -t
sudo nginx -s reload

Verify the negotiated protocol rather than assuming it succeeded:

curl -sS --http2 -o /dev/null -w 'HTTP version: %{http_version}\n' https://example.com
curl -sS --http3-only -o /dev/null -w 'HTTP version: %{http_version}\n' https://example.com

The HTTP/2 result should report version 2; the HTTP/3-only command fails rather than silently falling back. The local curl build must include HTTP/3 support.

Check TLS ALPN negotiation with the correct server name:

openssl s_client -connect example.com:443 -servername example.com -alpn h2 </dev/null

During rollout, monitor error rates, TLS handshakes, UDP packet loss, latency, and the ratio of HTTP/2 to HTTP/3 requests. Keep TCP port 443 available for clients that cannot use QUIC.

Security and Operational Considerations

  • Firewall and load balancers: Permit UDP 443 through firewalls, security groups, and upstream load balancers. Opening only TCP 443 makes HTTP/3 unreachable.

  • TLS configuration: Use TLS 1.3 for QUIC. HTTP/2 can retain TLS 1.2 when compatibility requires it.

  • Certificate renewal: Ensure renewal reloads Nginx after replacing the certificate; otherwise workers can continue using the old certificate.

  • Early data: QUIC 0-RTT reduces latency but introduces replay risk. Enable it only when the application and security model tolerate replay.

  • Discovery: Browsers generally need an Alt-Svc advertisement or another HTTP/3 discovery mechanism before switching from HTTP/2 to HTTP/3.

  • Capacity: QUIC maintains per-connection state, so test worker counts, socket reuse, bandwidth, and packet loss rather than assuming TCP tuning directly applies.

Common Mistakes

  • Using only listen 443 ssl;: This enables TLS but does not enable HTTP/2 with the modern directive syntax.

  • Using http3 on; without listen ... quic: HTTP/3 requires a QUIC-enabled UDP listener.

  • Supporting only TCP 443: HTTP/3 uses UDP and fails at the network layer when UDP is blocked.

  • Treating old syntax as the preferred configuration: listen ... ssl http2 remains compatible, but http2 on; is preferred in Nginx 1.25.1+.

  • Ignoring the Nginx build: An unknown http3 directive means the binary is older than 1.25.0 or was built without the HTTP/3 module.

31

How to proxy WebSocket connections in Nginx?

WebSocket proxying in Nginx requires upgrading an HTTP connection to a persistent bidirectional tunnel by forwarding the Upgrade and Connection headers and using HTTP/1.1 to the upstream.

Read full answer

Applies toNginx 1.24+ (open source)

How It Works

Nginx terminates the client HTTP request, then sends an HTTP/1.1 request to the upstream with the WebSocket upgrade headers. If the upstream responds with 101 Switching Protocols, Nginx keeps the connection open and tunnels frames in both directions. Because WebSockets are long-lived, the default 60-second proxy timeouts usually need to be increased or the application must send periodic pings.

Required Directives

  • proxy_http_version 1.1; — WebSocket upgrades require HTTP/1.1.

  • proxy_set_header Upgrade $http_upgrade; — forwards the client’s requested protocol.

  • proxy_set_header Connection "upgrade"; — or a mapped value such as $connection_upgrade.

  • proxy_read_timeout and proxy_send_timeout — prevent idle connections from being closed too early.

  • proxy_buffering off; — useful for low-latency bidirectional traffic.

proxy_pass Path Behavior

  • location /ws/ with proxy_pass http://backend; preserves the original URI, so /ws/chat reaches the upstream as /ws/chat.

  • location /ws/ with proxy_pass http://backend/; strips the matched prefix, so /ws/chat reaches the upstream as /chat.

Load Balancing WebSockets

WebSockets are stateful connections, so choose an upstream strategy that keeps a client on one backend: - Use ip_hash or a consistent hash for simple affinity. - Use least_conn when connections are long-lived and unevenly distributed. - For Nginx Plus, sticky cookie is more reliable than IP-based affinity behind NAT.

Production Considerations

  • Terminate TLS at Nginx and proxy to backends over plain HTTP or internal TLS as appropriate.

  • Validate the Origin header in the application or with Nginx rules to reduce cross-site WebSocket hijacking risk.

  • Use limit_conn and limit_req on the upgrade endpoint to protect against connection floods.

  • Monitor active connections, upstream errors, 101 responses, and connection duration.

  • Ensure graceful reloads and upstream deploys do not abruptly drop active sockets; drain or notify clients where possible.

Code Example

events {
    worker_connections 1024;
}

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    upstream websocket_backend {
        least_conn;
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
    }

    server {
        listen 443 ssl;
        server_name example.com;

        ssl_certificate     /etc/nginx/ssl/example.com.crt;
        ssl_certificate_key /etc/nginx/ssl/example.com.key;

        location /ws/ {
            proxy_pass http://websocket_backend;
            proxy_http_version 1.1;

            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            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_read_timeout 3600s;
            proxy_send_timeout 3600s;
            proxy_buffering off;
        }
    }
}

Common Pitfalls

  • Forgetting proxy_http_version 1.1 causes Nginx to use HTTP/1.0 and the upgrade fails.

  • Leaving default timeouts in place closes idle WebSockets after 60 seconds.

  • Using round-robin load balancing for stateful WebSocket apps can route messages to the wrong backend.

  • Assuming proxy_pass trailing slashes do not matter; they change the upstream URI.

32

How do you configure gzip and Brotli compression in Nginx?

gzip and Brotli are HTTP content encodings that reduce response size by compressing response bodies. Nginx can compress responses dynamically, serve precompressed .gz or .br assets, and negotiate the encoding using Accept-Encoding.

Read full answer

Applies toNginx 1.24+; `ngx_http_gzip_static_module` and a compatible `ngx_brotli` build are required for the optional directives shown

How Compression Works

Nginx uses a master process to read the configuration and manage worker processes. Each worker runs an event-driven request loop, while the gzip or Brotli filter compresses eligible response bodies inside that worker. Compression consumes CPU and can temporarily delay other events handled by the same worker.

The client advertises supported encodings:

Accept-Encoding: gzip, br

Nginx normally prefers Brotli when both encodings are enabled and the client accepts both; gzip remains the fallback. Exact filter ordering should be verified in the deployed build, especially when precompressed assets are available.

  • One encoding per response: Nginx returns one compressed representation, not both gzip and Brotli bodies.

  • Fallback: If the client accepts neither enabled encoding, Nginx returns the uncompressed response.

  • MIME filtering: Dynamic compression applies only to configured content types.

  • Precompressed assets: gzip_static and brotli_static select .gz or .br files only when the client accepts the corresponding encoding.

Important Directives

These directives are supported in http, server, and location contexts:

  • gzip on: Enables dynamic gzip compression.

  • gzip_comp_level 6: Sets a gzip level from 1 to 9; 6 is a common CPU/bandwidth compromise.

  • gzip_min_length 256: Ignores responses shorter than 256 bytes.

  • gzip_types ...: Defines MIME types eligible for dynamic gzip compression.

  • gzip_vary on: Adds Vary: Accept-Encoding to gzip responses.

  • gzip_proxied any: Allows compression of responses obtained through a reverse proxy.

  • gzip_static on: Serves a precompressed .gz file when present and accepted by the client.

  • brotli on: Enables dynamic Brotli compression.

  • brotli_comp_level 6: Sets a Brotli level from 0 to 11; higher levels generally require more CPU.

  • brotli_min_length 256: Sets the minimum response length considered for Brotli compression.

  • brotli_types ...: Defines MIME types eligible for dynamic Brotli compression.

  • brotli_static on: Serves a precompressed .br file when present and accepted by the client.

Code Example

This example enables both encodings and uses one Vary policy for negotiated responses:

http {
    include /etc/nginx/mime.types;

    gzip on;
    gzip_vary off;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_static on;
    gzip_types
        text/html
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/json
        application/xml
        application/rss+xml
        image/svg+xml;

    brotli on;
    brotli_comp_level 6;
    brotli_min_length 256;
    brotli_static on;
    brotli_types
        text/html
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/json
        application/xml
        application/rss+xml
        image/svg+xml;

    add_header Vary Accept-Encoding always;

    server {
        listen 80;
        server_name example.com;

        root /var/www/html;
        index index.html;

        location / {
            try_files $uri $uri/ =404;
        }
    }
}

Validate and reload the configuration:

sudo nginx -t && sudo nginx -s reload

Create a sufficiently large test file and query the local server explicitly:

sudo install -d -m 0755 /var/www/html
sudo truncate -s 4096 /var/www/html/style.css

curl -sS -D - -o /dev/null \
  --resolve example.com:80:127.0.0.1 \
  -H 'Accept-Encoding: gzip' \
  http://example.com/style.css

curl -sS -D - -o /dev/null \
  --resolve example.com:80:127.0.0.1 \
  -H 'Accept-Encoding: br' \
  http://example.com/style.css

The responses should contain Content-Encoding: gzip and Content-Encoding: br, respectively, along with Vary: Accept-Encoding.

Production Considerations

  • Prefer precompressed assets for static content: Generate .br and .gz files during the build and deploy them atomically with the corresponding source files.

  • Monitor CPU and latency: Brotli levels 10 and 11 can consume substantial CPU, particularly on busy workers.

  • Protect shared caches: Cache keys or Vary handling must prevent a Brotli body from reaching a client that cannot decode it.

  • Avoid already-compressed formats: Images, video, archives, WOFF2, and similar formats generally gain little from another compression pass.

  • Avoid double compression: Nginx does not recompress a response that already has a valid Content-Encoding header.

  • Consider side channels: Compressing responses containing secrets alongside attacker-controlled reflected data can create a BREACH-style attack surface.

Common Pitfalls

  • Unknown gzip_static or brotli directive: The required modules were not built into the installed Nginx binary. Inspect nginx -V and its build configuration.

  • Missing MIME type: Compression uses the response’s actual MIME type, so include every deployed type, such as both text/javascript and application/javascript.

  • Small test response: A response below the configured minimum length is not compressed, even when Accept-Encoding is present.

  • Stale precompressed assets: A .br or .gz file that outlives its source file can serve obsolete content; validate variants during deployment.

33

How do you set caching headers for static assets in Nginx?

Cache-Control on static assets is the main mechanism for controlling browser and intermediary-cache reuse. In Nginx, use expires for simple freshness lifetimes and add_header for complete directives such as public and immutable.

Read full answer

Applies toNginx 1.24+ (open source and NGINX Plus)

Where the headers come from

  • expires <time>: for a duration such as 30d, 12h, or 1y, sets Expires and Cache-Control: max-age=<seconds>. max uses ten years, epoch emits an expired timestamp with Cache-Control: no-cache, and off suppresses both headers.

  • add_header Cache-Control "..." [always]: emits the complete Cache-Control value, allowing directives such as public, immutable, no-cache, and stale-while-revalidate. always also adds the header to error responses such as 404 and 503.

  • etag on|off (default on): enables the static-file ETag and If-None-Match handling, allowing a matching validator to produce 304 Not Modified.

  • if_modified_since exact|before (default before): controls If-Modified-Since. With before, a response is unchanged when Last-Modified is not newer than the supplied timestamp, including an exact match; exact requires equality.

  • gzip_vary on (default on): adds Vary: Accept-Encoding to compressed responses so caches distinguish encoding variants.

Cache-Control values that matter

Value Effect Typical use
max-age=31536000 Fresh for one year without revalidation Versioned CSS, JavaScript, and images
immutable Signals that the representation will not change while fresh Fingerprinted assets such as app.9f3a12.css
public Allows storage by shared caches when otherwise cacheable Public static content
no-cache May be stored, but must be validated before reuse HTML shells and entry documents
no-store Must not be stored or reused Sensitive and authenticated responses
must-revalidate Prohibits stale reuse without successful validation Responses with a usable validator
stale-while-revalidate=60 Allows stale reuse during background revalidation where supported Non-critical assets

Browser caching vs Nginx caching

These are separate layers. expires and add_header control what clients and CDNs store. To cache upstream responses in Nginx, use the proxy_cache_* directives on a proxy_pass location:

  • proxy_cache_path defines the cache zone, capacity, and eviction parameters.

  • proxy_cache_keys defines the cache key; the default is commonly sufficient for static public content.

  • proxy_cache_valid 200 10m sets a fallback lifetime for a response status, unless response caching headers or another override specify otherwise.

  • proxy_cache_lock on makes concurrent requests wait for one upstream request to populate a missing cache entry, reducing cache stampedes.

  • Nginx does not cache responses with Set-Cookie or Vary: * by default.

  • open_file_cache caches file metadata rather than HTTP responses.

Code Example

server {
    listen 80;
    server_name www.example.com;

    root /var/www/html;
    index index.html;

    # Fingerprinted assets: cache publicly without revalidation while fresh.
    location /assets/ {
        expires off;
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        access_log off;
        try_files $uri =404;
    }

    # HTML entry point: store it, but validate it before reuse.
    location = /index.html {
        expires off;
        add_header Cache-Control "no-cache" always;
        try_files $uri =404;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}

When only a one-year lifetime is required, expires is shorter and does not create a second Cache-Control field:

location /assets/ {
    expires 1y;
}

This emits both Expires and Cache-Control: max-age=31536000; use the add_header form when public or immutable is also required.

Best practices and pitfalls

  • Version immutable assets: use content-hashed filenames or safe query-string versions. Otherwise, clients may retain obsolete assets for the full max-age.

  • Check add_header inheritance: a location that defines any add_header does not inherit outer-level add_header directives. Shared security headers should therefore be included in every relevant block.

  • Use no-cache for reusable HTML: it permits storage but requires validation. Use no-store for sensitive responses unless browser caching is explicitly safe.

  • Avoid redundant directives: must-revalidate does not make no-cache less restrictive and is normally unnecessary with it.

  • Preserve content variants: keep gzip_vary on when responses vary by Accept-Encoding.

  • Validate and inspect: run sudo nginx -t && sudo nginx -s reload, then use curl -I http://www.example.com/assets/app.css. Repeat the request with the returned ETag in If-None-Match to verify a 304 Not Modified response.

34

How does Nginx proxy caching work?

Nginx proxy caching stores eligible upstream responses on disk and serves matching requests from the cache, reducing upstream load and response latency. Cache metadata and keys are coordinated between workers through a shared-memory zone.

Read full answer

Applies toNginx open source 1.24+; Nginx Plus current supported releases

How It Works

  • The Nginx master process reads the configuration and manages worker processes. Event-driven workers handle requests, perform upstream I/O, and access cached files asynchronously.

  • proxy_cache_path defines the cache directory, keys_zone shared-memory area, cache-key levels, size limit, and inactive timeout. Response bodies are stored on disk; keys and metadata are stored in shared memory.

  • On a cache miss, Nginx proxies the request upstream and stores the response when it is cacheable. On a hit, Nginx reads the stored body and metadata from disk.

  • A cache-loader process loads persisted keys and metadata into shared memory at startup. A cache-manager process enforces the configured size limit and removes inactive data.

  • Only GET and HEAD responses are cacheable by default. Status codes and upstream headers such as Cache-Control, Expires, and X-Accel-Expires also affect caching and lifetime.

  • X-Accel-Expires takes precedence over Expires and Cache-Control; Expires takes precedence over Cache-Control.

Key Directives and URI Handling

  • proxy_cache: enables caching in a location and selects the zone defined by proxy_cache_path.

  • proxy_cache_key: defines the key hashed to locate an entry. Its default is $scheme$proxy_host$request_uri; $proxy_host comes from proxy_pass, not from the client Host header.

  • proxy_cache_valid: assigns fallback TTLs by response status when upstream headers do not supply a caching lifetime.

  • proxy_cache_use_stale: permits stale responses for configured conditions such as errors, timeouts, or selected HTTP status codes. The updating parameter is required to serve stale data while an update is in progress.

  • proxy_cache_background_update: refreshes an expired entry in a background subrequest while stale data is served.

  • proxy_cache_lock: allows only one worker to populate an expired entry; other workers wait up to the configured timeout.

  • proxy_cache_revalidate: sends conditional requests using If-Modified-Since or If-None-Match when refreshing an expired entry.

  • proxy_cache_bypass prevents reading from the cache but does not prevent storing the response. proxy_no_cache prevents storing but does not bypass cache reads.

The URI passed upstream depends on the proxy_pass form:

Configuration for request /api/users Upstream URI
proxy_pass http://backend; /api/users
proxy_pass http://backend/; /users

The second form replaces the matching /api/ location prefix with /. The default cache key uses $request_uri, which remains the original client URI including its query string, so rewritten upstream URIs do not automatically produce different cache keys.

Cache Statuses and Invalidation

$upstream_cache_status identifies cache activity:

Status Meaning
MISS No usable entry existed; Nginx fetched from upstream
HIT The response was served from cache
EXPIRED The entry was expired and Nginx fetched from upstream
STALE A stale response was served because an allowed error condition occurred
UPDATING A stale response was served while a background update ran
BYPASS Cache reading was bypassed by proxy_cache_bypass
REVALIDATED An expired entry was successfully revalidated with 304 Not Modified

Open-source Nginx has no built-in on-demand purge API, so common invalidation methods are TTL expiry, key versioning, or controlled cache-zone replacement. Nginx Plus supports cache purging through its HTTP API. Avoid deleting individual files while Nginx is running because shared-memory metadata may continue to reference them.

Production Security and Operations

  • Include the normalized client $host in the cache key when responses vary by virtual host; add a port only when it is semantically significant. Do not rely on the default $proxy_host for multi-tenant traffic.

  • Exclude authenticated, private, and personalized responses from caching using both bypass and no-cache conditions. Never share a cached response containing Set-Cookie or user-specific content.

  • Nginx does not automatically create separate entries for every arbitrary Vary dimension. Avoid caching Vary: * responses unless the application and key strategy are explicitly designed for it.

  • Treat query strings and arbitrary request headers as high-cardinality cache inputs; they can reduce hit ratios and must be normalized or allow-listed.

  • Monitor $upstream_cache_status in access logs, upstream latency, cache-hit ratio, disk usage, inode usage, and worker saturation.

  • Size the shared-memory zone for the number of keys, not response size. Keep sufficient disk headroom because the configured max_size is not a substitute for filesystem capacity alerts.

Common Pitfalls and Troubleshooting

  • A low hit ratio commonly results from uncacheable upstream headers, varying query strings, bypass conditions, or caching many near-unique URLs.

  • Repeated upstream requests for one expired object indicate a cache stampede. Verify proxy_cache_lock is enabled and that its timeout is appropriate.

  • Unexpectedly stale responses may be caused by proxy_cache_use_stale, long TTLs, or failed background updates. Correlate status values with upstream errors and logs.

  • If a reload introduces cache errors, run nginx -t before reloading and verify that the cache directory exists, is writable by the worker user, and is on a filesystem that supports efficient file creation, renaming, and deletion.

35

How does Nginx proxy caching use proxy_cache_key and bypass rules?

proxy_cache_key identifies the cache entry associated with a request. proxy_cache_bypass determines whether an existing cached response may be used, while proxy_no_cache determines whether a response received from the upstream may be stored.

Read full answer

Applies toNGINX Open Source 1.24+

How the Proxy Cache Works

For a location with proxy_cache enabled, NGINX generally follows this flow:

  1. It computes a cache key from proxy_cache_key.

  2. It looks for a matching cached response.

  3. If the entry exists and bypass conditions are false, NGINX returns the cached response.

  4. Otherwise, it forwards the request to the upstream.

  5. If the upstream response is cacheable and proxy_no_cache conditions are false, NGINX stores it.

A bypass does not delete an existing cache entry; it only prevents that request from using it. It also does not, by itself, prevent the upstream response from being stored.

proxy_cache_key

The default key is:

$scheme$proxy_host$request_uri

Important components include:

  • $scheme: Separates HTTP and HTTPS cache entries.

  • $proxy_host: Separates traffic sent to different proxy_pass targets.

  • $request_uri: The original request URI, including the query string. Different query parameters normally create different cache entries.

A custom key should also include $host when one upstream target serves multiple virtual hosts. Include $request_method if methods other than GET and HEAD are cached; otherwise, responses from different methods could collide.

$request_uri reflects the client’s original request. This matters when proxy_pass rewrites the upstream URI:

  • proxy_pass http://backend; forwards the request URI unchanged.

  • proxy_pass http://backend/api/; replaces the matching location prefix with /api/.

  • With the default key, the cache key still contains the client’s original URI.

Bypass and No-Cache Rules

Directive Evaluated against Effect
proxy_cache_bypass Request Prevents a cached response from being used for that request
proxy_no_cache Request or upstream response Prevents the upstream response from being written to the cache

A bypass condition is active when its value is nonempty and not "0". These directives accept variables and can appear in http, server, or location contexts.

For example:

  • Cached hit, bypass off: NGINX serves the cached response.

  • Cached hit, bypass on: NGINX contacts the upstream.

  • Cache miss, no-cache off: NGINX fetches and stores the upstream response.

  • Cache miss, no-cache on: NGINX fetches the response but does not store it.

proxy_no_cache does not prevent an existing cache hit from being served. To keep authenticated requests out of a shared cache entirely, apply the relevant condition to both proxy_cache_bypass and proxy_no_cache.

Production Failure Modes

  • Personalized-data leakage: Sharing a key across users can expose one user’s response to another. Prevent both reads and writes for authenticated traffic, or include every relevant representation dimension in the key.

  • Excessive cache cardinality: Arbitrary query strings can consume disk and metadata memory while producing few useful hits.

  • Cache stampedes: Many simultaneous misses can overload the upstream. Use proxy_cache_lock.

  • Stale content: Short TTLs improve freshness but reduce hit ratio. Controlled proxy_cache_use_stale behavior improves availability.

  • Disk exhaustion: Configure max_size and monitor cache-manager eviction behavior.

  • Unclear invalidation: proxy_cache_bypass and proxy_no_cache do not purge entries. Use TTLs, controlled key versioning, or a supported purge mechanism.

Code Example

Place this configuration in an http-included file such as /etc/nginx/conf.d/cache-example.conf:

proxy_cache_path /var/cache/nginx
    levels=1:2
    keys_zone=app_cache:10m
    max_size=1g
    inactive=60m
    use_temp_path=off;

map $http_authorization $skip_cache {
    default 0;
    "~." 1;
}

map $upstream_http_set_cookie $skip_store {
    default 0;
    "~." 1;
}

upstream backend {
    server 10.0.0.10:8080;
    keepalive 16;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_cache app_cache;
        proxy_cache_key "$scheme|$request_method|$host|$request_uri";
        proxy_cache_methods GET HEAD;
        proxy_cache_valid 200 10m;

        # Do not read cached responses for authenticated requests.
        proxy_cache_bypass $skip_cache;

        # Do not store authenticated responses or responses with Set-Cookie.
        proxy_no_cache $skip_cache $skip_store;

        proxy_cache_lock on;
        proxy_cache_use_stale error timeout updating
            http_500 http_502 http_503 http_504;

        add_header X-Cache-Status $upstream_cache_status always;
    }
}

Ensure /var/cache/nginx is writable by NGINX’s service account, then validate and reload:

sudo nginx -t
sudo systemctl reload nginx

Best Practices and Troubleshooting

  • Monitor the $upstream_cache_status values HIT, MISS, BYPASS, EXPIRED, and STALE.

  • Never cache personalized responses unless the key includes every dimension that changes the representation.

  • Do not use proxy_ignore_headers Set-Cookie for personalized APIs; it can cause sensitive responses to be shared.

  • Treat bypass headers from untrusted clients carefully: they can intentionally increase origin traffic.

  • Confirm that authentication, cookies, Host, query parameters, and HTTP method are handled consistently by the cache key.

36

What is microcaching in NGINX?

Microcaching is the practice of caching dynamic HTTP responses for a very short period, typically one to five seconds. It collapses bursts of similar requests into fewer upstream requests, reducing origin load and latency at the cost of briefly stale data.

Read full answer

Applies toNGINX OSS 1.24+ and NGINX Plus R15+

What It Is and How NGINX Executes It

NGINX has a master process that reads the configuration and manages worker processes. Workers handle connections with an event-driven loop, allowing one worker to manage many connections without dedicating a thread to each one.

For proxy caching, metadata and cache keys are held in a shared memory zone so all workers see the same cache. Response bodies are normally stored on disk and managed by the cache manager, which removes inactive or excess data according to the configured limits.

Microcaching uses the same proxy_cache mechanism as longer-lived caching; only the TTL is short. It is separate from browser caching, a CDN, limit_req rate limiting, response compression, TLS termination, and HTTP/2 or HTTP/3 negotiation.

Request Flow and Configuration Scope

A typical cached request flow is:

  1. The first request receives MISS and is sent to the upstream.

  2. NGINX stores the response in the cache zone.

  3. Later requests receive HIT until the TTL expires.

  4. With proxy_cache_lock on, one request populates or refreshes the entry while concurrent requests wait instead of causing a cache stampede.

The cache is configured within an http, server, or location context. NGINX first selects the virtual server from the request host and then selects a location. Exact matches using = take precedence; otherwise NGINX remembers the longest prefix match and checks regular expressions in configuration order, unless the prefix uses ^~ to stop regex matching.

With proxy_pass pointing to an upstream without a URI suffix, NGINX forwards the original request URI. A URI suffix, such as /service/, replaces the matching location prefix in the upstream request. This distinction must also be considered when designing cache keys.

The default proxy_cache_key includes the scheme, upstream host and port, and request URI including its query string. It does not include cookies or request headers such as Authorization.

TTLs, Revalidation, and Stale Responses

proxy_cache_valid sets fallback caching durations for selected status codes. Response headers such as Cache-Control, Expires, or X-Accel-Expires generally take priority, so a one-second directive does not guarantee exactly one second of freshness.

Important directives include:

  • proxy_cache_revalidate: Revalidates expired entries with conditional requests using If-None-Match or If-Modified-Since.

  • proxy_cache_background_update: Starts a background refresh for stale content. Pair it with proxy_cache_use_stale updating if clients should receive stale content while the refresh runs.

  • proxy_cache_use_stale: Allows stale data during specified upstream failures or updates, but only when a stale cached entry exists.

  • proxy_cache_lock_timeout: Limits how long requests wait for another request to populate an entry before attempting the upstream themselves.

Responses containing Set-Cookie, Cache-Control: private, Cache-Control: no-store, or Vary: * are normally not cached. Cache-Control: no-cache can also prevent storage unless the cache policy is deliberately adjusted.

Security and Design Choices

Microcaching must never mix responses belonging to different users. Requests with cookies or other personalization headers should normally bypass the cache. Do not assume that adding Authorization to the cache key makes authorized-response caching safe: NGINX normally does not cache responses to requests carrying an Authorization header, and an authorized request must not be allowed to receive an unrelated cached entry. Use proxy_cache_bypass to prevent cache reads and proxy_no_cache to prevent cache writes where appropriate.

Scenario Suitability Reason
Public, frequently repeated dynamic API Good Short bursts can share one backend response
Personalized or authenticated API Usually unsuitable Requires explicit bypass or safe isolation
Static assets Usually unnecessary Browser and CDN caching are generally more effective
Real-time pricing or inventory Conditional Even a short TTL may violate freshness requirements
Sudden backend traffic spike Good Cache locks and stale serving reduce origin pressure

Production Checklist and Common Pitfalls

  • Monitor cache-hit ratio, upstream latency and errors, disk usage, and inode consumption. The $upstream_cache_status log field distinguishes statuses such as HIT, MISS, BYPASS, EXPIRED, STALE, UPDATING, and REVALIDATED.

  • Prevent cache stampedes with proxy_cache_lock, and size proxy_cache_lock_timeout for realistic upstream latency.

  • Avoid unbounded key cardinality from arbitrary query strings or user identifiers, which can reduce hit ratios and consume storage.

  • Test simultaneous expiry, upstream failures, revalidation, authentication bypass, and stale-data behavior before rollout.

  • Treat the cache as disposable data, not a system of record. Validate configuration with nginx -t, reload workers gracefully, and invalidate or version keys when response formats change.

37

How do you configure Nginx request rate limiting with limit_req?

limit_req implements per-key request-rate limiting using a leaky-bucket algorithm. Define a shared-memory zone with limit_req_zone, then enforce it with limit_req in an appropriate server or location block.

Read full answer

Applies toNginx OSS 1.24+

How It Works

  • limit_req_zone: Defines the rate and the key used to identify clients. It must appear in the http context.

  • limit_req: Enables enforcement for a server or location. Multiple worker processes coordinate through the shared-memory zone.

  • rate: Specifies the request rate for each key, such as 10r/s.

  • burst: Allows temporary excess requests above the configured rate. Without nodelay, excess requests are delayed; with nodelay, requests up to the burst capacity are processed immediately.

  • Rejected requests: Return 503 by default. Set limit_req_status 429 to return the more appropriate Too Many Requests response.

  • Keying: $binary_remote_addr limits each client IP independently. The zone is local to each Nginx instance, not shared across a cluster.

Nginx uses a master process to manage worker processes. Workers run an event-driven, non-blocking request-processing model and update the limiter’s shared-memory state, so limits remain consistent across workers.

Code Example

The following is a complete configuration that passes nginx -t when installed in the standard Nginx directory structure:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    # Allow temporary bursts above 10 requests per second per client IP.
    limit_req_zone $binary_remote_addr zone=api_per_ip:10m rate=10r/s;

    log_format limit_log '$remote_addr $status $request_time '
                         'limit_status=$limit_req_status "$request"';

    access_log /var/log/nginx/limit.log limit_log;

    upstream api_backend {
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
        keepalive 32;
    }

    server {
        listen 8080;
        server_name example.com;

        location /api/ {
            limit_req zone=api_per_ip burst=20 nodelay;
            limit_req_status 429;
            limit_req_log_level warn;

            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
        }

        location / {
            return 200 "ok\n";
        }
    }
}

Validate and apply the configuration:

sudo nginx -t && sudo systemctl reload nginx

Location lookup is hierarchical: an exact (=) match wins immediately; otherwise, Nginx selects the longest matching prefix location. If that prefix uses ^~, regular-expression locations are skipped. Otherwise, regular-expression locations are tested in configuration order, and the first match wins. If none matches, the prefix location is used.

Production Security

  • Trusted proxies: Behind a load balancer, $remote_addr may be the proxy’s address. Configure set_real_ip_from with only the proxy’s CIDR and set real_ip_header X-Forwarded-For.

  • Header sanitization: The trusted proxy must overwrite X-Forwarded-For with the canonical client address or otherwise sanitize and order it correctly. set_real_ip_from trusts the peer address; it does not sanitize the header itself.

  • Spoofing risk: Do not use $http_x_forwarded_for directly unless the request came through a trusted proxy. Attackers could otherwise bypass or poison the limit by forging the header.

  • User-level limits: For authenticated APIs, key by a verified user or tenant ID where possible. Do not trust an unvalidated client-supplied header such as X-User-ID.

  • Clustered deployments: Each Nginx node enforces its own local limit. Use a gateway or distributed rate-limiting service when the limit must be global.

  • Zone sizing: Start with a zone such as 10m, but size it for the expected number of active keys and monitor memory usage.

Operational Behavior and Troubleshooting

  • $limit_req_status: Logged values include PASSED, DELAYED, and REJECTED, making limiter behavior visible in access logs.

  • Dry run: limit_req_dry_run on; logs the decision without delaying or rejecting requests, which is useful before enforcing a new policy.

  • Monitoring: Track rejection rates, 429 responses, request latency, upstream saturation, and the ratio of DELAYED to PASSED requests.

  • Capacity planning: Choose rate from measured traffic and service objectives. Increase burst only when short legitimate spikes are expected; a large burst can permit substantial instantaneous load.

  • Restart behavior: Limiter state is in memory and resets when Nginx restarts. Validate configurations on staging, run nginx -t, and use a graceful reload to avoid unnecessary disruption.

  • Different limit types: limit_req controls request rate. Use limit_conn when the requirement is to limit concurrent connections; it does not directly cap concurrent HTTP/2 request streams.

38

How does limit_conn restrict client connections in Nginx?

limit_conn limits the number of simultaneous connections associated with a key, such as a client IP address. It protects resources by returning a configurable status code when the limit is exceeded; it controls concurrency rather than requests per second.

Read full answer

Applies toNginx 1.24+

How It Works

  • limit_conn_zone creates a shared-memory zone that stores connection counters for a defined key.

  • limit_conn applies a maximum concurrent connection count to one or more keys in that zone.

  • Nginx uses a master process and worker processes. The shared zone lets all workers maintain a consistent count instead of enforcing separate per-worker limits.

  • If a client already has 10 connections and the limit is 10, the next connection is rejected with the configured status code.

  • The default rejection status is 503 Service Unavailable, although limit_conn_status 429 is often more appropriate for throttling.

  • For HTTP/2 and HTTP/3, concurrent requests on one multiplexed connection are counted as separate connections by this module.

This is a concurrency control mechanism, not a request-rate limiter. Use limit_req when the requirement is to limit requests over time.

Key and Scope Behavior

  • $binary_remote_addr uses the binary representation of the client address and avoids unnecessary string-storage overhead.

  • A constant key can implement a global limit across all clients, while a variable such as $server_name is more appropriate for a per-server limit.

  • If the same zone is referenced by multiple location blocks, their connection counters are shared.

  • The zone is defined in the http context, while limit_conn can be applied at http, server, or location scope.

  • The limit counts active connections, not cumulative connections. Long-lived keepalive connections can therefore continue occupying slots.

Production and Security Considerations

  • Proxy or load-balancer deployments: Nginx normally sees the proxy’s IP as $remote_addr. Configure Nginx’s real_ip module with only trusted proxy addresses, or define a custom key from a header that the edge infrastructure controls. Never trust arbitrary X-Forwarded-For values.

  • Shared NAT addresses: Multiple legitimate users behind one corporate or mobile NAT address share a counter. Choose a higher limit or a more appropriate key when this causes false positives.

  • HTTP/2 and HTTP/3: Because requests are multiplexed, a limit intended for HTTP/1 TCP connections may be much lower for modern multiplexed protocols.

  • Monitoring: Track rejection status codes in the access log and limit-related messages in the error log. Correlate rejections with latency, worker load, upstream saturation, and connection counts.

  • Safe rollout: limit_conn_dry_run on counts connections that would exceed the limit without rejecting them. Use dry-run mode to estimate the correct threshold before enforcing it.

  • Capacity planning: Choose a sufficiently large shared-memory zone for expected key cardinality. An undersized zone can prevent new states from being tracked reliably.

  • Layered protection: limit_conn does not replace upstream timeouts, connection limits, request-rate limiting, or edge-level DDoS controls.

Common Pitfalls

  • Confusing limit_conn per_ip 10 with a limit of 10 total requests.

  • Placing limit_conn_zone inside a server block; that directive must be in the http context.

  • Treating the zone size, such as 10m, as the connection limit rather than shared-memory capacity.

  • Forgetting that long-lived keepalive connections continue to occupy connection slots.

39

How do you allow or block IP addresses in Nginx?

Nginx permits or denies client addresses with the allow and deny directives from ngx_http_access_module. The first matching rule wins; for large or generated rulesets, geo, map, firewall, or edge controls are more appropriate.

Read full answer

Applies toNginx 1.24+

How allow/deny Work

  • allow and deny are valid in http, server, location, and limit_except contexts.

  • Rules are checked in configuration order, and the first matching rule decides the result. If no rule matches, access is allowed.

  • Addresses may be individual IPv4 or IPv6 addresses, CIDR ranges, or all.

  • Configuration forms a hierarchy of http blocks containing server blocks and location blocks. Nginx first picks the server block by listening address and port, then by server_name (falling back to the default_server). Inside it, an exact = location is used immediately; otherwise Nginx remembers the longest matching prefix and tests regular-expression locations in configuration order. The first matching regex wins, unless the remembered prefix uses ^~; if no regex matches, the prefix is used.

Common Patterns and Proxy Safety

  • Allowlist: permit trusted addresses first, then use deny all; as the final rule.

  • Blocklist: deny unwanted addresses and omit deny all;, because unmatched addresses are allowed by default.

  • Edge filtering: use cloud security groups, a WAF, or host firewalls for volumetric attacks; per-request Nginx matching is not a substitute for upstream DDoS protection.

  • Large or generated lists: use geo with CIDR ranges, ranges, include files, or its proxy and proxy_recursive parameters, then use the resulting variable in map or a simple if containing return.

Behind a proxy, $remote_addr initially contains the proxy’s address. Build Nginx with ngx_http_realip_module, configure every trusted proxy using set_real_ip_from, and select the header with real_ip_header. Trust only known proxy addresses; otherwise, clients can spoof forwarded headers and bypass the rules.

Production Context

  • Nginx uses a master process to read configuration and manage workers. Workers use event-driven, non-blocking I/O to handle many connections efficiently.

  • Serve static files with root, alias, and try_files; use proxy_pass for reverse proxying and upstream groups for load balancing.

  • TLS requires appropriate certificate and private-key directives. HTTP/2 normally uses ALPN over TLS; Nginx 1.25.1+ supports http2 on;, while Nginx 1.24 uses listen 443 ssl http2;. HTTP/3 requires Nginx 1.25+ built with HTTP/3 and compatible QUIC support.

  • proxy_cache and proxy_cache_path provide response caching. gzip or brotli can reduce transfer sizes, but already-compressed assets should be excluded.

  • Use limit_req_zone with limit_req for request-rate control and limit_conn for connection limits. Add security headers such as X-Content-Type-Options, Referrer-Policy, and an application-appropriate CSP; enable HSTS only when HTTPS is reliable across the required domain.

  • Access logs record response status, while the access module logs access forbidden by rule to error_log at error level. Monitor both logs alongside worker, connection, and upstream-latency metrics.

Code Example

# /etc/nginx/conf.d/access.conf
# This file must be included from nginx.conf's http { } context.

geo $blocked_ip {
    default             0;
    198.51.100.0/24     1;
    203.0.113.42        1;
}

upstream backend {
    server 10.0.0.20:8080;
    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    # Trust only the immediate reverse proxy.
    set_real_ip_from 10.0.0.10;
    real_ip_header X-Forwarded-For;

    location /admin/ {
        # Allowlist the office network and one administrator.
        allow 10.0.0.0/16;
        allow 203.0.113.10;
        deny  all;

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend;
    }

    location / {
        # A geo value of "0" is false; "1" triggers the response.
        if ($blocked_ip) {
            return 403;
        }

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend;
    }
}

Best Practices and Pitfalls

  • Validate before reloading: run nginx -t, inspect the effective configuration with nginx -T, and then run nginx -s reload.

  • A graceful reload lets old workers finish existing requests while new workers start, so old and new configurations can briefly coexist.

  • Test restrictions from hosts with the relevant source addresses, using curl --interface where possible. curl --resolve changes the destination address and does not simulate a different client source IP.

  • Include both IPv4 and IPv6 networks in allowlists when both address families are reachable; a final deny all; covers otherwise-unmatched IPv6 clients.

  • Keep large lists in included files, validate each revision, reload gracefully, and monitor denied-request rates and upstream impact.

40

How do you configure Nginx basic authentication?

Basic authentication in Nginx uses auth_basic with an auth_basic_user_file containing password hashes. Nginx challenges unauthenticated clients with HTTP 401 and validates credentials before serving the protected resource.

Read full answer

Applies toNginx 1.24+ (open source; HTTP/3 requires Nginx 1.25+ and a compatible build)

How It Works

The ngx_http_auth_basic_module handles authentication during request processing:

  1. A client requests a protected resource without credentials.

  2. Nginx returns 401 Unauthorized with WWW-Authenticate: Basic realm="...".

  3. A browser prompts for the username and password and retries with an Authorization: Basic ... header.

  4. Nginx compares the supplied credentials with the password file.

Basic authentication only Base64-encodes credentials; it does not encrypt them. It must therefore be used over HTTPS.

Nginx has a master process that reads the configuration and manages workers. Workers accept connections and process requests with an event-driven, non-blocking architecture. A graceful reload starts workers with the new configuration while allowing old workers to finish active requests.

auth_basic and auth_basic_user_file are valid in http, server, and location contexts and inherit through those levels. Nginx checks exact = matches first, then finds the longest prefix match. Unless that prefix uses ^~, Nginx checks regular-expression locations in configuration order and uses the first match; otherwise it uses the remembered prefix.

Code Example

Install the password utility:

# Ubuntu 22.04/24.04
sudo apt-get install -y apache2-utils

# RHEL 9
sudo dnf install -y httpd-tools

Create the password file and add users. Use -c only when intentionally creating or rebuilding the file:

sudo htpasswd -B -c /etc/nginx/.htpasswd alice
sudo htpasswd -B /etc/nginx/.htpasswd bob

The -B option stores bcrypt hashes rather than plaintext passwords.

Grant the Nginx workers read access using their actual group:

# Ubuntu typically uses www-data
sudo chown root:www-data /etc/nginx/.htpasswd

# RHEL typically uses nginx
# sudo chown root:nginx /etc/nginx/.htpasswd

sudo chmod 0640 /etc/nginx/.htpasswd
ps -o user,group,comm -C nginx

Configure a protected static location:

# /etc/nginx/conf.d/basic-auth.conf
server {
    listen 127.0.0.1:8080;
    server_name example.com;

    root /var/www/html;

    location /protected/ {
        auth_basic "Restricted area";
        auth_basic_user_file /etc/nginx/.htpasswd;

        try_files $uri $uri/ =404;
        add_header Cache-Control "private, no-store" always;
    }
}

Create a test file, validate, reload, and test authentication:

sudo install -d -m 0755 /var/www/html/protected
printf 'Protected content\n' |
  sudo tee /var/www/html/protected/index.txt >/dev/null

sudo nginx -t
sudo systemctl reload nginx
# curl prompts for alice's password
curl --user alice \
  http://127.0.0.1:8080/protected/index.txt

Proxy Path Behavior

When protecting a reverse-proxied application, the trailing slash in proxy_pass changes the forwarded URI:

Configuration Original request URI sent upstream
proxy_pass http://127.0.0.1:8080/; /protected/reports /reports
proxy_pass http://127.0.0.1:8080; /protected/reports /protected/reports

With the trailing slash, Nginx replaces the matching /protected/ location prefix with /. Without it, the original request URI is preserved. This distinction commonly causes upstream 404 responses.

For a cached proxy location, prevent responses associated with an Authorization header from entering or using the shared cache:

proxy_cache_bypass $http_authorization;
proxy_no_cache $http_authorization;

Production Security and Operations

  • TLS: Use listen 443 ssl; with ssl_certificate and ssl_certificate_key in the server block. Redirect plaintext traffic with return 301 https://$host$request_uri;. After HTTPS is stable, add add_header Strict-Transport-Security "max-age=31536000" always;.

  • Password file: Treat /etc/nginx/.htpasswd as a secret, restrict its permissions, and keep encrypted backups. Losing it requires resetting affected users.

  • Monitoring: Authentication failures are recorded as 401 responses in the access log. Alert on sustained 401 rates and investigate abnormal 5xx rates. Never log the Authorization header or plaintext passwords.

  • Rate limiting: limit_req runs before Basic authentication and therefore limits all requests to the protected location, not only failed logins. For example, define limit_req_zone $binary_remote_addr zone=auth_per_ip:10m rate=5r/s; in http and apply limit_req zone=auth_per_ip burst=10 nodelay; in the location. Behind a trusted proxy, configure set_real_ip_from and real_ip_header so clients are not all grouped under the proxy address.

  • Load balancing: If multiple Nginx instances enforce authentication, each must receive the same password file or a centrally managed equivalent. Health checks should use an appropriate internal route rather than being treated as failed authentication.

  • HTTP versions: Basic authentication behaves the same over HTTP/2 and HTTP/3. HTTP/2 is normally used over TLS with ALPN. Open-source Nginx introduced HTTP/3 in 1.25.0, but support also requires a compatible QUIC-enabled build.

  • Compression: gzip compresses response bodies; it does not encrypt request headers or protect Basic credentials.

  • Inheritance: A nested location can accidentally disable inherited authentication with auth_basic off. Review the effective configuration using nginx -T.

  • Stronger authentication: For human access at scale, consider OIDC, OAuth 2.0, or mTLS instead of Basic authentication.

Troubleshooting

  • All requests return 401: Verify the username and password hash, confirm that the password file contains the expected records, and check whether the browser cached stale credentials.

  • Requests return 500: Inspect the error log for an unreadable password file or unsupported hash. nginx -t validates configuration syntax but does not prove that workers can read the file or that the platform’s crypt() implementation supports its hash format.

  • Only some paths bypass authentication: Review exact, prefix, and regex location matching and nested auth_basic off directives.

  • Existing users disappear: Running htpasswd -c again truncates the file. Use it only when intentionally rebuilding the password file.

41

Which security headers should Nginx send?

A hardened Nginx deployment should normally send a focused set of security headers. They reinforce HTTPS, restrict browser capabilities, and reduce exposure to clickjacking, MIME sniffing, cross-origin abuse, and content injection, but their exact values must match the application’s authentication, embedding, payment, OAuth, and third-party integration requirements.

Read full answer

Applies toNginx 1.24+

Baseline Headers

Header Typical value Purpose and considerations
Strict-Transport-Security max-age=31536000; includeSubDomains Instructs browsers to use HTTPS for the domain. Add includeSubDomains only when every relevant subdomain supports HTTPS. Add preload only after meeting the browser’s preload requirements.
Content-Security-Policy Application-specific Restricts scripts, styles, frames, forms, and other resource loads. It is a major defense against cross-site scripting, although an overly restrictive policy can break the application.
X-Content-Type-Options nosniff Prevents browsers from guessing a response’s MIME type and interpreting it as executable content.
Referrer-Policy strict-origin-when-cross-origin Limits URL disclosure through the Referer header while retaining useful same-origin information.
X-Frame-Options DENY or SAMEORIGIN Provides legacy clickjacking protection. Modern browsers use CSP’s frame-ancestors; keeping both is useful for older clients, and their policies should remain compatible.
Permissions-Policy camera=(), geolocation=(), microphone=() Disables browser capabilities the application does not need. Expand this list with other features, such as payment or USB access, when necessary.
X-XSS-Protection 0 Disables obsolete browser XSS auditors that can introduce vulnerabilities. Effective XSS protection comes from CSP and secure application code.

Cross-Origin Headers

Header Typical value Purpose and considerations
Cross-Origin-Opener-Policy same-origin Isolates the browsing context from cross-origin windows. Consider same-origin-allow-popups when OAuth, payment, or other identity flows require an opener relationship.
Cross-Origin-Resource-Policy same-origin Prevents other origins from loading protected resources. Change or omit it for assets that must be consumed cross-origin.
Cross-Origin-Embedder-Policy require-corp Optional. It enables stronger cross-origin isolation but can prevent cross-origin resources from loading unless they explicitly opt in.

Access-Control-Allow-Origin is not a universal security header. Configure CORS only for explicitly trusted origins, and never combine a wildcard origin with credentialed requests.

Nginx Behavior

  • Adding headers with always makes Nginx emit them for successful responses and error responses.

  • Nginx-level add_header directives are inherited only when the child context defines no add_header directives of its own. A location with its own headers can therefore lose the inherited baseline.

  • An upstream application may already emit CSP, HSTS, or CORS headers, resulting in duplicates. Establish one authoritative owner and use proxy_hide_header only when Nginx intentionally replaces an upstream header.

  • HSTS delivered over plain HTTP is ignored by browsers. Redirect HTTP to HTTPS and send HSTS over a valid HTTPS response. ACME challenge paths may need an HTTP exception.

  • Hiding the Nginx version with server_tokens off reduces version disclosure, but the Server header can still identify Nginx.

Rollout and Operations

  • Test CSP with Content-Security-Policy-Report-Only first, monitor violations, and then enforce the final policy.

  • Test authenticated pages, uploads, downloads, redirects, error pages, OAuth flows, embedded content, and third-party assets.

  • Review CSP reports, browser errors, authentication failures, and Nginx access logs after each policy change.

  • Treat CSP, COOP, CORP, and COEP as coordinated policies: changing one can invalidate assumptions in the others.

  • Remember that security headers supplement TLS, secure cookies, input validation, authorization, content sanitization, and a WAF; they do not replace those controls.

42

How do you hide the Nginx version number?

The Nginx version is exposed in the Server response header and in default error pages, and you control it with the server_tokens directive. Setting server_tokens off; removes the version number while keeping the generic nginx product name, which is the standard hardening step.

Read full answer

Applies toNginx 1.24+ (open source and commercial; `server_tokens` is a core directive)

How It Works

By default, server_tokens is on, so responses include a header like Server: nginx/1.24.0 and error pages print the version. With server_tokens off;, Nginx emits only Server: nginx and omits the version from generated error pages. The directive is valid in the http, server, and location contexts, and the most specific scope wins, so you can disable it globally and re-enable it only where needed.

Configuration

Place the directive in the http block of /etc/nginx/nginx.conf so it applies to every virtual host:

http {
    server_tokens off;

    server {
        listen 80;
        server_name example.com;
        ...
    }
}

After editing, validate and reload without dropping connections:

sudo nginx -t && sudo nginx -s reload

Code Example

A minimal hardened server block combining version hiding with common security headers:

server {
    listen 443 ssl http2;
    server_name example.com;

    server_tokens off;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
    }
}

Verify the result with curl:

curl -I https://example.com

You should see Server: nginx with no version, and no version in the body of a 404 response.

Limitations and Hardening

  • server_tokens off; hides the version but not the product name. Fully removing nginx from the Server header requires the third-party headers-more-nginx-module (more_clear_headers Server;) or stripping it at an upstream proxy; that is usually unnecessary and adds operational complexity.

  • Version disclosure is a low-severity information leak, but it aids attackers in targeting known CVEs, so hiding it is good hygiene alongside patching.

  • Do not rely on obscurity: keep Nginx updated regardless of whether the version is visible.

  • Custom error pages (error_page) replace the default ones entirely, which also removes version strings; combine them with server_tokens off; for defense in depth.

Best Practices

  • Set server_tokens off; once in the http block rather than repeating it in every server block.

  • Always run nginx -t before reloading to catch syntax errors.

  • Pair version hiding with a patching and monitoring routine: track the installed version internally even though it is not advertised.

  • Avoid leaking the version through other channels such as build metadata in response bodies or verbose upstream error messages.

43

How do you configure Nginx access and error logs?

Nginx writes request records to an access log and operational diagnostics to an error log; configure them with the access_log and error_log directives, usually in the http, server, or location context.

Read full answer

Applies toNginx 1.24+ (open source)

How It Works

  • access_log path [format] [buffer=size] [flush=time] [if=condition]; records each request. The default is logs/access.log combined.

  • error_log file [level]; records startup, configuration, and runtime errors. The default is logs/error.log error.

  • log_format name '...'; defines a named format using variables such as $remote_addr, $request, $status, and $request_time.

  • Multiple access_log or error_log directives can be used at the same level to write to several destinations.

  • Error levels are debug, info, notice, warn, error, crit, alert, and emerg; debug requires an Nginx build with debug support.

Common Configuration

Use a custom text format for operators and a JSON format for log aggregation. Conditional logging can skip noisy or sensitive requests.

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent"';

    log_format json escape=json '{'
        '"time":"$time_iso8601",'
        '"remote_addr":"$remote_addr",'
        '"request":"$request",'
        '"status":$status,'
        '"body_bytes_sent":$body_bytes_sent,'
        '"request_time":$request_time'
    '}';

    map $request_uri $loggable {
        ~*token= 0;
        default 1;
    }

    access_log /var/log/nginx/access.log main buffer=64k flush=5s if=$loggable;
    error_log /var/log/nginx/error.log warn;

    server {
        listen 80;
        server_name example.com;

        access_log /var/log/nginx/example.access.log json;
        error_log /var/log/nginx/example.error.log info;

        location / {
            root /var/www/example;
        }
    }
}

Operational Notes

  • buffer and flush reduce disk I/O by batching writes; use them for high-traffic sites, but expect a short delay before entries appear.

  • if=$variable logs only when the variable is non-empty and not 0; use a map to implement sampling or redaction rules.

  • Nginx does not rotate logs itself. Use logrotate and reopen logs with nginx -s reopen or USR1.

  • Worker processes must have write permission to the log directory; check ownership, SELinux contexts, and available disk space during incidents.

  • Error logs are the first place to look for upstream timeouts, TLS handshake failures, permission errors, and configuration mistakes.

Log Rotation Example

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /usr/sbin/nginx -s reopen >/dev/null 2>&1 || true
    endscript
}

Best Practices

  • Validate configuration with nginx -t before reloading.

  • Use structured JSON logs when shipping to Elasticsearch, Loki, or a SIEM.

  • Avoid logging secrets such as tokens, session IDs, or authorization headers.

  • Keep error log level at warn or error in production unless actively debugging.

  • Monitor log volume, disk usage, and reopen behavior after rotation.

44

How do you create a custom Nginx access log with response times?

A named custom access-log format is created with log_format and attached to a context with access_log. Use $request_time for end-to-end request duration and $upstream_*_time variables to identify time spent connecting to and receiving responses from upstreams.

Read full answer

Applies toNginx 1.24+ on Linux (HTTP/3 requires Nginx 1.25+ and a QUIC-enabled build)

How It Works

Nginx has a master process that reads configuration and manages worker processes. Workers use an event-driven, non-blocking event loop to handle connections concurrently and write access-log records when requests finish.

log_format is defined in the http context. access_log can be set at http, server, or location scope, allowing a global format with selective overrides.

Variable Meaning
$request_time Time from reading the first client bytes until sending the last response bytes, in seconds with millisecond resolution
$upstream_connect_time Time spent establishing the upstream connection
$upstream_header_time Time spent receiving upstream response headers
$upstream_response_time Time spent obtaining the upstream response, including upstream processing and network time

These timing values are empty when no upstream was contacted. If retries or multiple upstream servers were involved, upstream timing variables can contain multiple values separated by commas and colons.

Code Example

Add the following inside the existing http {} context:

# JSON-escape variable values so user-controlled data remains valid JSON.
log_format app_timing escape=json
    '{'
    '"timestamp":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":$status,'
    '"bytes_sent":$body_bytes_sent,'
    '"request_time":"$request_time",'
    '"upstream_connect_time":"$upstream_connect_time",'
    '"upstream_header_time":"$upstream_header_time",'
    '"upstream_response_time":"$upstream_response_time",'
    '"upstream_addr":"$upstream_addr",'
    '"user_agent":"$http_user_agent"'
    '}';

# Apply the custom format to servers in this http context.
access_log /var/log/nginx/access.json app_timing;

upstream app_backend {
    server 10.0.0.10:8080;
    server 10.0.0.11:8080;
    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    location /api/ {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;

        # Do not trust an arbitrary inbound X-Forwarded-For header.
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Validate the complete installed configuration before reloading it:

# Reload only when validation succeeds.
sudo nginx -t && sudo systemctl reload nginx

With location /api/ and proxy_pass http://app_backend;, the original URI is forwarded unchanged, such as /api/orders. With proxy_pass http://app_backend/;, the matched /api/ prefix is replaced by /, so /api/orders becomes /orders.

Production and Operational Controls

  • Server and location matching: Server blocks separate virtual hosts; locations select request handling. Nginx checks exact matches, the longest prefix, and then regular expressions unless the prefix uses ^~.

  • Static content: Use root and try_files for local files. Use proxy_pass only for dynamic upstream handling.

  • Load balancing: Nginx defaults to weighted round-robin and supports least_conn, weights, and passive failure handling with max_fails and fail_timeout. Active health checks require Nginx Plus or a third-party module.

  • TLS and protocols: For Nginx 1.24, use listen 443 ssl http2; from Nginx 1.25.1, use listen 443 ssl with http2 on. HTTP/3 requires Nginx 1.25+, a QUIC-enabled build, listen 443 quic reuseport, http3 on, and firewall access for UDP port 443. Inspect the build with nginx -V.

  • Caching and compression: Configure proxy_cache_path and proxy_cache for eligible responses. gzip is built in; Brotli requires a compatible third-party module. Compression consumes CPU and should be monitored.

  • Rate limiting and headers: Use limit_req_zone with a shared memory zone and apply it with limit_req. Add headers such as X-Content-Type-Options, Referrer-Policy, and Content-Security-Policy; enable HSTS only after HTTPS is reliable.

  • Logging privacy: escape=json prevents variable values from breaking JSON records. Avoid logging cookies, authorization headers, or secrets. $request includes the query string; use $uri when arguments must not be recorded.

  • Operations: Monitor request rates, 4xx/5xx rates, timing percentiles, upstream failures, and log-disk usage. Rotate and retain logs appropriately, back up configuration and TLS keys securely, test upgrades with nginx -t, and reload gracefully.

  • Trusted proxies: If Nginx is behind a trusted load balancer, restore the client address with set_real_ip_from and real_ip_header before using $remote_addr in X-Forwarded-For.

Troubleshooting and Common Pitfalls

  • Missing or empty log: Confirm the path, directory, and permissions for the account that starts Nginx. The master normally opens access-log files before workers run.

  • Empty upstream timings: The request was handled locally or served from cache without contacting an upstream.

  • High $request_time with low upstream timing: Investigate slow client reads or writes, slow request-body transfer, and Nginx processing rather than backend latency.

  • High upstream timing: Compare $upstream_connect_time with $upstream_header_time to distinguish connection delay from slow backend or network processing.

  • Validation limits: nginx -t checks syntax and referenced files, but it does not prove backend reachability, adequate disk capacity, or correct runtime behavior.

45

How do you safely test and reload Nginx configuration?

Nginx configuration changes should be validated with nginx -t before a graceful reload (nginx -s reload or systemctl reload nginx), which replaces worker processes without dropping active connections.

Read full answer

Applies toNginx 1.24+ (open source) on Linux (systemd-based distributions).

How It Works

Nginx runs a single master process that reads configuration and manages one or more worker processes that handle connections. A reload does not restart the master; instead, the master re-reads the configuration, spawns new workers with the new config, and gracefully shuts down the old workers once their in-flight connections finish. This means active requests are not dropped and listening sockets are not closed.

Under the hood, the master validates the re-read configuration, starts new workers, tells old workers to stop accepting new connections, and lets old workers finish existing requests before exiting. If the new configuration cannot bind a listener, the reload fails and the previous workers remain active. Some directives, such as daemon, master_process, and pid, require a full restart rather than a reload; nginx -t will not warn about this.

Testing the Configuration

Always validate before reloading. nginx -t parses every included file and checks syntax plus basic semantic validity, such as whether referenced files exist.

  • nginx -t — test the default config (/etc/nginx/nginx.conf).

  • nginx -t -c /path/to/nginx.conf — test an alternate config file.

  • nginx -T — dump the fully merged, effective configuration (useful for debugging include ordering).

  • nginx -t -q — quiet mode; only prints errors.

A successful test prints syntax is ok and test is successful. A failure prints the file and line number; no reload should be attempted until it passes.

Reloading Safely

Once the test passes, apply the change with a signal to the master:

  • sudo nginx -s reload — sends HUP to the master process recorded in the PID file.

  • sudo systemctl reload nginx — preferred on systemd hosts; equivalent to the above and integrates with service state.

  • sudo kill -HUP $(cat /run/nginx.pid) — manual fallback when the PID file path differs.

The reload is asynchronous: the command returns immediately while workers swap in the background. There is no built-in flag to wait for reload completion.

Failure Modes and Common Mistakes

  • Reloading without testing — a syntax error can prevent new workers from starting; the master keeps old workers, but you may not notice until traffic fails.

  • Port conflicts — binding to a port already in use causes the reload to fail; check journalctl -u nginx and nginx -t.

  • Long-lived connections — WebSockets, SSE, or large uploads keep old workers alive for a long time; monitor old workers with ps (they show as nginx: worker process is shutting down); stub_status reports connection counts, not workers.

  • Permission/ownership changes — new log or cache directories must be writable by the worker user (www-data or nginx).

  • Missing include files — nginx -t catches these when the include path is evaluated; always run it after editing.

  • Assuming reload applies everything — directives such as daemon, master_process, and pid require a full restart; nginx -t will not tell you this.

Best Practices

  • Always run nginx -t in CI/CD before deploying config, and gate reloads on success.

  • Use systemctl reload nginx rather than raw signals in production for auditability.

  • Keep a backup of the previous config and know how to roll back (cp nginx.conf.bak nginx.conf && nginx -t && systemctl reload nginx).

  • Monitor worker count and connection metrics; alert if old workers linger after a reload.

  • For zero-downtime config changes involving new listeners, use nginx -s reload plus health checks on the new upstream.

Code Example

# Validate configuration
sudo nginx -t

# Dump effective merged config for debugging
sudo nginx -T | less

# Apply changes gracefully
sudo systemctl reload nginx

# Verify workers swapped (old PIDs should disappear)
ps -eo pid,ppid,cmd | grep '[n]ginx: worker'

# Roll back if needed
sudo cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
sudo nginx -t && sudo systemctl reload nginx
# /etc/nginx/nginx.conf (excerpt)
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
}
46

What changes during an Nginx reload versus restart?

An Nginx reload replaces the worker generation to apply a new configuration while the master and active workers remain available. An Nginx restart replaces the master and the entire instance, with connection impact determined by how the service manager stops Nginx.

Read full answer

Applies toNginx 1.24+ on Linux, including systemd-based distributions

Nginx Process Model

Nginx uses a master-worker architecture:

  • The master process reads and validates the configuration, manages workers, and handles signals.

  • Each worker process uses an event-driven event loop to handle many connections without allocating a thread to every connection.

  • During a reload, the master starts workers with the new configuration and asks workers running the old configuration to retire gracefully.

  • Replacement workers inherit the listening sockets, allowing new connections to be accepted without an intentional refusal window.

Old workers stop accepting new connections but continue draining active requests and upgraded connections such as WebSockets. Idle HTTP keepalive connections are closed gracefully, so their clients reconnect and enter the new worker generation.

What nginx -s reload Does

nginx -s reload sends SIGHUP to the Nginx master process. The master then:

  1. Re-reads and validates the configuration.

  2. Starts replacement workers using the new configuration.

  3. Gracefully asks the old workers to stop accepting new connections and finish their active work.

  4. Keeps the same master process and master PID.

If the new configuration is invalid, Nginx rejects it and continues running the previous configuration and workers. The validation error is written to the Nginx error log.

A reload does not replace the running executable. After upgrading the Nginx package, a normal reload therefore continues using the old binary; a full restart or a controlled binary-upgrade procedure is required.

What a Restart Does

There is no standard nginx -s restart command. A restart is normally performed with sudo systemctl restart nginx, which stops the existing service and then starts a new master and worker generation.

The behavior depends on the service unit’s stop mechanism:

  • A graceful stop using nginx -s quit allows active work to finish, but the old instance stops accepting new connections while draining.

  • A fast stop using nginx -s stop terminates Nginx immediately and can drop active connections.

  • Custom ExecStop hooks can have different behavior, so systemctl cat nginx should be inspected before relying on a graceful restart.

A restart recreates process-local and shared-memory runtime state. It is appropriate for activating a newly installed binary or recovering from persistent process-state problems, but it has greater connection and availability risk than a reload.

Behavior Comparison

Aspect Reload Restart
Master process Remains the same Replaced
Worker generation Replaced Replaced
Configuration Re-read and applied Loaded by the new master
Active connections Old workers drain them Drain only with a graceful stop
Idle keepalive connections Closed so clients reconnect Closed or dropped, depending on stop mode
New connections Normally continue without a refusal window May encounter a startup gap
Invalid configuration Previous configuration remains active Old instance may already be stopped
Binary upgrade Does not activate the new binary Activates the installed binary
Runtime state Master remains; workers are replaced Process and shared-memory state are recreated

Production Practices and Failure Modes

  • Validate first: Run sudo nginx -t before either operation. A restart can otherwise leave the old instance stopped when the new configuration fails validation.

  • Prefer reloads for configuration changes: The normal sequence is sudo nginx -t && sudo nginx -s reload.

  • Inspect service behavior: Review the unit with systemctl cat nginx to determine whether restarts drain or abruptly terminate connections.

  • Watch long-lived connections: WebSockets and other upgraded connections can keep retiring workers alive and delay their exit.

  • Roll out incrementally: Drain one instance from the load balancer, apply the change, verify health and logs, and then continue with the remaining instances.

  • Monitor actively: Check the Nginx error log, systemd journal, request-failure rate, active connections, worker lifecycle, and upstream latency during and after the operation.

  • Maintain rollback material: Back up configuration and package versions before an upgrade, and verify that the rollback configuration also passes nginx -t.

47

How do you debug Nginx 502 Bad Gateway errors?

A 502 Bad Gateway means Nginx received an invalid or incomplete response from an upstream server. Debug it by tracing the request from the Nginx worker process through its upstream connection, then checking Nginx logs, upstream reachability, application logs, and network policy.

Read full answer

Applies toNginx OSS 1.24-1.28

What the Error Means

Nginx’s proxy module connects to the selected upstream, forwards the request, and expects a valid HTTP response. It returns 502 when it cannot complete that exchange—for example, when the connection is refused, an upstream closes prematurely, or an upstream sends malformed HTTP.

A timeout normally produces 504 Gateway Timeout, not 502. However, some application and proxy failures can close the connection early and appear as 502.

Nginx uses a master process and worker processes. Each worker handles many connections through an event-driven, non-blocking architecture, so the 502 is usually associated with one upstream attempt rather than an entire Nginx instance being down.

Debugging Workflow

  1. Confirm which configuration is active

bash sudo nginx -t sudo nginx -T 2>&1 | less

nginx -t validates syntax but does not test upstream connectivity. nginx -T displays the complete effective configuration, including included files.

  1. Reproduce the request locally

bash curl -v --max-time 5 \ --resolve example.com:80:127.0.0.1 \ http://example.com/health

--resolve sends the correct Host header while targeting the local Nginx instance. Check whether the failure is consistent or only affects certain paths, methods, headers, or client addresses.

  1. Inspect Nginx errors

bash sudo tail -F /var/log/nginx/error.log

Useful messages include:

  • connect() failed (111: Connection refused): nothing is listening on that address or port.

  • Permission denied: the upstream socket is inaccessible to the Nginx worker.

  • no live upstreams: all configured servers have been marked unavailable by passive failure handling.

  • upstream prematurely closed connection: the application or an intermediate proxy disconnected early.

  • invalid upstream response: the upstream returned malformed HTTP.

  • TLS or certificate errors: TLS negotiation with the upstream failed.

  • Test the upstream directly from the Nginx host

bash curl -v --max-time 5 http://10.0.0.10:8080/health sudo ss -lntp

Run the test from the Nginx host, not only from an administrator’s workstation. Network security groups, firewalls, service meshes, and routing rules may permit one location but block another. An HTTP response such as 404 still proves basic network connectivity.

  1. Correlate with application logs

Check whether the request reached the application, was rejected during startup, exhausted a connection pool, crashed, or was terminated by a deployment. Compare timestamps, request IDs, traceparent, and the upstream address.

Common Causes

Cause Typical evidence Corrective action
Wrong upstream host or port Connection refused Correct the upstream configuration
Application not listening No socket in ss output Start or rebind the application
Firewall or security-group rejection Timeout or unreachable Allow traffic only from Nginx
Invalid DNS or missing resolver DNS-related error log Fix DNS or configure resolver correctly
Application crash or early close Upstream logs stop at request receipt Inspect application crashes and shutdowns
Malformed upstream response Invalid HTTP error Fix the application or intermediary proxy
Stale or overloaded connections Intermittent failures under load Review pooling and connection limits
Unix socket permission failure Permission denied Correct socket ownership and Nginx user access
TLS handshake failure Certificate or protocol error Correct certificates, protocols, and trust chain

For proxy_pass, trailing slashes affect URI replacement. With location /api/ and proxy_pass http://backend/, the /api/ prefix is replaced by /, so /api/users reaches the upstream as /users. With proxy_pass http://backend—no URI—the original normalized request URI (/api/users) is passed unchanged. A path mismatch here usually shows up as an upstream 404, not a 502.

Code Example

The following configuration is valid for Nginx 1.24+ and exposes useful upstream timing and status fields:

log_format upstream_timing
    '$remote_addr - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent '
    'upstream=$upstream_addr '
    'upstream_status=$upstream_status '
    'upstream_time=$upstream_response_time';

upstream app_backend {
    server 10.0.0.10:8080 max_fails=2 fail_timeout=10s;
    server 10.0.0.11:8080 max_fails=2 fail_timeout=10s;
    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example.access.log upstream_timing;

    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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_connect_timeout 2s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
}

Reload only after validation:

sudo nginx -t && sudo systemctl reload nginx

Production Practices

  • Monitor the upstream separately: Alert on the rate of 502 responses, not only total Nginx traffic. Track $upstream_status, $upstream_addr, and $upstream_response_time.

  • Avoid masking failures: proxy_next_upstream can retry another server, but excessive retries increase latency and may duplicate non-idempotent operations. Use them deliberately and configure application-level idempotency.

  • Control access: Keep upstream ports private, require TLS where traffic crosses untrusted networks, and expose only Nginx to the public client.

  • Manage changes safely: Back up configuration, run nginx -t, reload rather than restart when possible, and retain the previous configuration for rollback.

  • Prepare for incidents: Correlate Nginx logs with application, load-balancer, container, and network logs. Record whether failures affect one backend, every backend, one route, or only requests with particular headers or bodies.

48

How do you troubleshoot a 504 Gateway Timeout in Nginx?

A 504 Gateway Timeout returned by Nginx means it could not complete the upstream exchange within the applicable timeout, commonly while connecting or waiting for response headers. The application or an outer load balancer may also return its own 504, while a body-read timeout after headers have been forwarded usually appears as a truncated response rather than a 504.

Read full answer

Applies toNGINX 1.24+ on Linux, with typical reverse-proxy upstreams

What the Error Means

NGINX uses a master process and worker processes. Workers use an event-driven model to accept connections, read requests, and communicate with upstreams without dedicating a thread to every connection.

For a proxied request, NGINX may return 504 because:

  • It could not establish an upstream connection within proxy_connect_timeout.

  • It exceeded proxy_read_timeout while waiting for response headers.

  • Transmitting the request to the upstream exceeded proxy_send_timeout.

  • The application itself returned an HTTP 504, which Nginx passes through.

  • A downstream dependency made the application exceed the outer load balancer’s timeout, so that load balancer returned 504 before Nginx did.

proxy_read_timeout is an inactivity timeout between reads, not a strict total request-duration limit. A slow but continuous response can therefore run longer than this value.

Debugging Workflow

  1. Identify where the 504 originated. Inspect the response headers and NGINX logs. An NGINX-generated timeout usually appears in error.log as upstream timed out. A $upstream_status of 504 means the upstream returned that status.

  2. Confirm the active configuration. Runtime configuration may differ from the file you expect:

bash sudo nginx -t sudo nginx -T 2>&1 | less

  1. Reproduce the request directly against NGINX:

bash curl -sv --noproxy '*' --connect-timeout 3 --max-time 40 \ -H 'Host: example.com' http://127.0.0.1:8080/api/health

  1. Test the upstream independently:

bash curl -sv --noproxy '*' --connect-timeout 3 --max-time 40 \ http://10.0.0.10:8080/api/health

A direct timeout points toward the application or its network path rather than NGINX. 5. Inspect saturation and reachability. Check active connections, queueing, pod or instance health, DNS, routing, and application logs. Correlate the timestamp with deployments, dependency failures, lock contention, garbage-collection pauses, or resource exhaustion. 6. Measure each phase. NGINX timing variables distinguish connection establishment, upstream header wait, and total request duration.

Reading the Evidence

Observation Likely cause Next action
$upstream_connect_time is high Network, routing, overloaded upstream, or connection exhaustion Check ss -lntp, firewall rules, routing, and upstream capacity
$upstream_header_time is high Application or dependency is slow Inspect application traces, database latency, locks, and downstream calls
$upstream_response_time is high but header time is low Slow response body or streaming Check application throughput and client download speed
$upstream_status is 504 Upstream generated the response Search upstream and dependency logs
Direct upstream request times out Failure exists before NGINX Escalate to the application or network owner
Only some instances fail One upstream instance is unhealthy Remove or restart the bad instance and check health checks

Code Example

The following configuration records upstream timings and uses bounded connection and inactivity timeouts:

worker_processes auto;

error_log /var/log/nginx/error.log warn;

events {
    worker_connections 4096;
}

http {
    log_format upstream_timing
        '$remote_addr "$request" status=$status '
        'request_time=$request_time upstream_status=$upstream_status '
        'upstream_addr=$upstream_addr '
        'connect_time=$upstream_connect_time '
        'header_time=$upstream_header_time '
        'response_time=$upstream_response_time';

    access_log /var/log/nginx/access.log upstream_timing;

    upstream app_backend {
        server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    server {
        listen 8080;
        server_name example.com;

        location /api/ {
            proxy_pass http://app_backend;
            proxy_http_version 1.1;

            proxy_set_header Host $host;
            proxy_set_header Connection "";

            proxy_connect_timeout 2s;
            proxy_send_timeout 10s;
            proxy_read_timeout 30s;
        }
    }
}

Here, proxy_pass http://app_backend; preserves the original /api/... request URI. Adding a URI such as proxy_pass http://app_backend/; replaces the matched /api/ prefix with /, which can cause incorrect routes.

Validate before reloading:

sudo nginx -t && sudo systemctl reload nginx

Failure Modes and Best Practices

  • Do not fix a 504 by simply increasing every timeout. Align NGINX timeouts with the client, outer load balancer, and application budgets.

  • Treat proxy_next_upstream retries carefully. Retrying non-idempotent operations can duplicate writes unless the application provides idempotency.

  • For streaming or long-polling responses, evaluate proxy_buffering off, but do not use it as a generic remedy for slow applications.

  • Monitor 5xx rates, upstream latency, connect time, response time, active connections, and upstream health. NGINX access logs should exclude credentials and sensitive headers.

  • During an incident, mitigate first: roll back a bad deployment, scale healthy instances, shed noncritical traffic, or route around the failing backend. Preserve logs and timing evidence before restarting affected processes.

49

What causes an Nginx 413 error, and how do you fix it?

An HTTP 413 Request Entity Too Large response means that a request body exceeded a configured size limit. In Nginx 1.24+, the usual fix is to raise client_max_body_size at the appropriate scope and align any limits enforced by the application, gateway, CDN, or another proxy.

Read full answer

Applies toNginx 1.24+ (open-source edition)

Causes and Inheritance

  • Nginx limit exceeded: The default client_max_body_size is 1m. Nginx rejects a body larger than the effective limit.

  • Upstream limit exceeded: The application, API gateway, CDN, or another reverse proxy may return the 413 after Nginx forwards the request.

  • Scope mismatch: client_max_body_size can be set at http, server, or location scope. A location with its own value replaces the inherited value.

  • Unexpected upload: A client may send the wrong file, corrupt data, or exceed the endpoint’s intended policy.

  • Chunked transfer: A request without Content-Length is still checked. With buffering disabled, Nginx may discover the violation only after streaming part of the body upstream.

  • Default request buffering: With proxy_request_buffering on, Nginx buffers the complete request body before proxying it. Oversized bodies are then rejected before the complete request reaches the upstream, although they can consume memory or temporary disk space.

Diagnosing the Source

Do not identify the source from Server: nginx alone. Nginx can add that header to an upstream-generated 413 response.

  • Check the Nginx error log for a locally generated rejection, such as client intended to send too large body.

  • Compare the Nginx access log with application and gateway logs.

  • If the log format includes $upstream_status, a value of 413 indicates that the upstream returned the error; it is empty for most Nginx-generated responses.

  • Inspect client_max_body_size in every relevant http, server, and location block.

  • Reproduce the request with the same payload size, headers, and transfer encoding as the failing client.

Code Example

The following is a complete minimal main configuration that can pass nginx -t; in production, merge its http contents into the existing configuration:

# /etc/nginx/nginx.conf
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    upstream backend_pool {
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            # Accept request bodies up to 25 MiB.
            client_max_body_size 25m;
            proxy_pass http://backend_pool;

            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

For route-specific limits, an exact block such as location = /upload/ can set client_max_body_size 50m, while another location retains its inherited or explicitly configured limit.

Test, diagnose, and reload safely:

# Show the response status/headers and the uploaded payload size.
curl -v -X POST --data-binary @payload.bin http://example.com/upload/
wc -c payload.bin

# Reload only if the configuration test succeeds.
sudo nginx -t && sudo nginx -s reload

Production Practices and Pitfalls

  • Align every layer: Raising the Nginx limit does not change limits enforced by the application, gateway, load balancer, CDN, or WAF.

  • Avoid unlimited uploads: client_max_body_size 0 disables the limit but can expose public endpoints to accidental oversized uploads, slow-request attacks, and resource exhaustion.

  • Control buffering: Monitor the default or configured client_body_temp_path and its filesystem capacity. Consider proxy_request_buffering off only when upstream streaming is designed for partial requests.

  • Set timeout semantics deliberately: client_body_timeout limits the interval between successive body reads, not the total upload duration. Coordinate it with client_header_timeout, proxy timeouts, and client behavior.

  • Monitor rejections: Track 413 counts by route, client, and upstream status. Alert on sustained increases while distinguishing local rejections from upstream failures.

  • Avoid accidental URI rewriting: proxy_pass http://backend_pool; preserves the original request URI, while a trailing slash can replace a matching location prefix. This does not alter the body-size limit but can expose unrelated endpoint bugs.

  • Keep protocols consistent: The same body limit applies to HTTP/1.1, TLS, and HTTP/2 requests; test through every reverse proxy and load balancer in the production path.

50

How do you tune Nginx proxy timeouts?

Tune Nginx proxy timeouts by setting separate limits for upstream connection establishment, request transmission, and response reading. Choose values from observed latency and availability requirements rather than applying one large timeout to every route.

Read full answer

Applies toNGINX OSS 1.24+

Timeout Semantics

Nginx uses asynchronous, non-blocking upstream connections. Each connection has timers that trigger when the corresponding operation stalls.

Directive What It Measures Typical Value
proxy_connect_timeout Time allowed to establish the upstream connection 2s–5s
proxy_send_timeout Inactivity between writes to the upstream 15s–30s
proxy_read_timeout Inactivity between reads from the upstream 30s–60s

These are inactivity timeouts, not total request-duration limits. For example, proxy_read_timeout 30s permits a response that continuously sends data every 20 seconds even if the complete response takes several minutes.

If all three are omitted, Nginx normally uses 60s. An upstream timeout that occurs before response headers reach the client normally returns 504 Gateway Timeout; a refused upstream connection generally returns 502 Bad Gateway. If the upstream stalls after headers were sent, the client may retain 200 OK and observe a truncated response while Nginx logs an upstream timeout.

Choosing Timeout Values

  • Connection timeout: Keep it short for nearby or controlled backends. Large values can retain failed requests and consume concurrency during an outage.

  • Read timeout: Base it on the maximum expected gap between upstream response chunks, not average response time. Include network latency, database queries, and downstream dependencies.

  • Send timeout: Account for large uploads, slow backpressure, and network congestion. It does not limit how long the client takes to upload the body to Nginx.

  • Route-specific behavior: Use tighter timeouts for health checks and fast APIs, but longer values for report generation or other known slow operations.

  • Long-lived streams: WebSockets, Server-Sent Events, and gRPC need heartbeat traffic or specialized timeout settings; otherwise an otherwise healthy idle connection can be terminated.

Production Failure Modes

  • Increasing timeouts reduces false 504 responses but allows failed or slow requests to occupy resources longer.

  • Retries multiply effective latency. If proxy_next_upstream includes timeout, a request may reach several backends before failing.

  • proxy_next_upstream_timeout can limit the total retry period; use it when bounded failover is preferable.

  • Health checks: max_fails and fail_timeout implement passive failure detection. NGINX OSS 1.27.3+ also supports active checks with the health_check directive; earlier OSS releases are passive-only.

  • Client-side slowdowns are separate concerns. Tune client_body_timeout, client_header_timeout, and send_timeout rather than weakening upstream proxy timeouts.

Protocol and Security Notes

HTTP/2 and HTTP/3 affect how clients connect to Nginx, but they do not change upstream proxy timer semantics. HTTP/3 also requires an Nginx build containing the QUIC module, which can be confirmed with nginx -V.

Client TLS negotiation has its own ssl_handshake_timeout; this is distinct from proxy_connect_timeout. Do not use large proxy timeouts as a substitute for rate limiting or request-size controls. Apply limit_req, limit_conn, and client_max_body_size where appropriate.

Code Example

The following configuration uses a three-second connection timeout and 30-second inactivity limits. Place it inside the http context:

upstream app_backend {
    server 10.0.1.10:8080 max_fails=3 fail_timeout=30s;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    location /api/ {
        # A URI is specified, so the matched /api/ prefix is replaced by /api/.
        # /api/orders is forwarded to the upstream as /api/orders.
        proxy_pass http://app_backend/api/;

        proxy_http_version 1.1;
        proxy_set_header Connection "";

        proxy_connect_timeout 3s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        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;
    }
}

With proxy_pass http://app_backend;, no URI is specified and the original normalized request URI is preserved. Validate and reload safely:

sudo nginx -t && sudo nginx -s reload

Best Practices

  • Establish a baseline from p95 and p99 latency, then monitor how often each route approaches its timeout.

  • Track $request_time, $upstream_connect_time, $upstream_header_time, $upstream_response_time, and $upstream_status in access logs or an OpenTelemetry integration.

  • Correlate proxy timeouts with upstream metrics, saturation, dependency latency, and error logs.

  • Change timeouts incrementally and compare 499, 502, and 504 rates as well as successful-request latency.

  • Use separate location blocks when routes have materially different processing or streaming characteristics.

51

How do Nginx worker_processes and worker_connections affect capacity?

In Nginx, worker_processes determines how many worker processes handle traffic, while worker_connections sets the maximum number of simultaneous connections each worker can manage. Together they establish an approximate connection-slot ceiling, not a direct HTTP request-throughput limit.

Read full answer

Applies toNginx Open Source 1.24+

What Each Directive Controls

Directive Context Default What it controls
worker_processes main 1 Number of worker processes created by the master process
worker_connections events 512 (packaged nginx.conf files often set 1024) Maximum simultaneous connections handled by each worker

The master process reads the configuration, binds privileged ports, starts workers, and coordinates reloads and shutdowns. Workers use an event-driven, non-blocking network model, so one worker can maintain many connections without assigning an operating-system thread to every connection.

worker_processes auto; normally selects workers according to the CPUs available to Nginx. In containers, verify the process CPU affinity and cgroup limits rather than assuming that the host’s CPU count is used. More workers can improve multicore throughput, but also consume more memory and scheduling resources; workers do not provide independent caches or strict workload isolation.

How Capacity Is Calculated

The theoretical upper bound is:

worker_processes × worker_connections

For example, 4 workers with 4,096 connections each provide 16,384 connection slots. This is not the number of clients that can always be served because listeners, internal resources, upstream connections, and persistent keepalive sockets also consume slots.

A reverse proxy commonly consumes two slots during an HTTP/1.x exchange:

  1. One downstream connection from the client to Nginx.

  2. One upstream connection from Nginx to the application.

Thus, 16,384 slots may support roughly 8,192 simultaneous HTTP/1.x proxy exchanges when every exchange requires a separate upstream connection. Idle clients need only their downstream slot, while upstream keepalive sockets remain in the budget until reused or closed. server and location blocks do not receive separate connection budgets.

Workload and Protocol Effects

Workload Connection-slot effect
Static file or TLS response One downstream connection; TLS additionally consumes handshake CPU and memory
HTTP/1.x reverse proxy Normally one downstream plus one upstream connection during the exchange
HTTP/2 downstream client One connection can carry multiple request streams, subject to protocol and stream limits
WebSocket Normally retains both downstream and upstream connections for the session
HTTP/3 Each logical QUIC connection consumes connection/state resources, while clients share UDP socket resources

HTTP/3 uses QUIC over UDP rather than ordinary TCP sockets. QUIC connections share the worker’s UDP socket, so they do not normally consume one file descriptor per client, although connection-state memory, packet processing, UDP load-balancer support, and socket configuration remain important.

Upstream keepalive can reduce repeated upstream connection establishment, but pooled sockets still occupy slots while open. The URI behavior of proxy_pass is independent of capacity: without a URI it forwards the original request URI, while with a URI it replaces the matching location prefix. Under location /api/, proxy_pass http://127.0.0.1:8080; forwards /api/users, whereas the trailing-slash form forwards /users.

Configuration and Validation

A practical starting point is worker_processes auto; in the main context and worker_connections 4096; in the events context. Validate the complete configuration before reloading it; the commands can be chained as sudo nginx -t && sudo nginx -s reload so that reload is attempted only after the test succeeds.

nginx -t checks syntax and attempts to open referenced files. nginx -T prints the complete loaded configuration, while nginx -V shows the compiled version and modules. A graceful reload starts workers with the new configuration while old workers finish serving existing clients.

Production Tuning and Failure Modes

  • File-descriptor limits: Ensure the worker’s RLIMIT_NOFILE has headroom over the connection budget using worker_rlimit_nofile or the service manager’s LimitNOFILE. Otherwise, Nginx may log too many open files.

  • Monitor real saturation: Track worker CPU and memory, request rate and latency, upstream latency, response errors, accepted connections, and file-descriptor usage. Use stub_status only if Nginx was built with ngx_http_stub_status_module; access and error logs are broadly available.

  • Account for processing costs: TLS handshakes, compression, caching, rate limiting, security-header processing, logging, and disk I/O can become bottlenecks even when connection slots remain available. Caching and compression can reduce upstream traffic but consume local resources.

  • Respect upstream limits: More Nginx capacity does not help if backends have insufficient CPU, memory, connection limits, or slow responses that tie up connections.

  • Plan reloads: Monitor both old and new workers during graceful reloads because long-lived and keepalive connections can extend the transition.

52

How do you tune Nginx for high-traffic production workloads?

Tune Nginx using capacity-based tuning: measure realistic traffic, size worker and file-descriptor limits, then tune proxying, buffering, caching, compression, TLS, and rate limiting. The objective is predictable latency and graceful degradation—not simply increasing worker counts or connection limits.

Read full answer

Applies toNginx OSS 1.24+ on Linux

Architecture and Capacity

  • The master process reads configuration, binds privileged ports, manages workers, and handles reloads or shutdowns.

  • Worker processes use an event-driven, non-blocking architecture with epoll on Linux. They can maintain many connections without one OS thread per connection.

  • worker_processes auto selects workers based on available CPUs. More workers help CPU-heavy workloads but also increase memory use and connection competition.

  • worker_connections limits each worker’s simultaneous connections, including upstream connections. A proxied request generally needs one client connection and one upstream connection, so 4,096 connections may support roughly 2,048 concurrent proxied requests.

  • Ensure worker_rlimit_nofile, the systemd LimitNOFILE, and the process’s hard file-descriptor limit are high enough. File-descriptor exhaustion appears as socket() failed (24: Too many open files).

Configuration and Request Flow

  • server blocks select a virtual host using address, port, and server_name. For locations, Nginx checks exact = matches first, remembers the longest prefix match, then evaluates regex locations in configuration order unless a ^~ prefix suppresses regex matching.

  • Serve static files with root, try_files, sendfile, and appropriate expires or Cache-Control. CDN offloading is usually preferable for globally popular assets.

  • proxy_buffering on protects upstreams from slow clients and can improve upstream throughput, but it may introduce disk I/O. Disable it for streaming or long-lived interactive responses.

  • proxy_read_timeout measures the interval between successive upstream reads, not the entire response duration.

  • With location /api/, proxy_pass http://backend; preserves /api/; proxy_pass http://backend/; replaces that prefix with /.

  • Use least_conn when upstream requests vary significantly in duration. OSS Nginx supports passive failure handling through max_fails and fail_timeout; active health checks require Nginx Plus.

Protocol, Cache, and Security Tuning

Area Production guidance
TLS Enable TLS 1.2 and 1.3, configure session resumption, rotate certificates safely, and monitor handshake failures.
HTTP/2 Nginx 1.24.x uses listen 443 ssl http2;. Nginx 1.25.1+ uses listen 443 ssl; with http2 on;.
HTTP/3 Use listen 443 quic reuseport; with http3 on; only when built and supported by the environment; retain TCP fallback.
Caching Use proxy_cache, proxy_cache_lock, and proxy_cache_use_stale. Avoid caching personalized responses and ensure the cache directory has adequate disk capacity.
Compression Prefer gzip or a compiled Brotli module for compressible responses, but benchmark CPU cost and avoid recompressing images or video.
Rate limiting Apply limit_req_zone with a deliberate rate, burst, and status such as 429. It is application abuse control, not a complete DDoS solution.
Headers Add HSTS only after HTTPS is stable, plus X-Content-Type-Options, X-Frame-Options, and an application-appropriate CSP.
Logging Log request time, upstream time, status, bytes, request ID, and upstream address. Do not log credentials or unnecessary personal data.

Operations and Failure Modes

Load-test the complete path, including TLS, caches, and realistic response sizes. Monitor CPU, memory, file descriptors, socket queues, upstream latency, request latency, 499, 502, 503, and 504 responses, and upstream saturation.

Back up configuration, validate it, canary changes where possible, and reload gracefully:

sudo cp -a /etc/nginx "/etc/nginx.backup.$(date +%F-%H%M%S)"
sudo nginx -t
sudo nginx -T
sudo systemctl reload nginx

A reload starts new workers while existing workers finish current connections. Keep the previous configuration available for rapid rollback. Investigate 502 for invalid upstream responses, 504 for upstream timeouts, and 503 for unavailable upstreams or rate limiting.

Code Example

This illustrative /etc/nginx/nginx.conf uses an upstream pool, upstream keepalive, static-file serving, request limiting, and buffered proxying:

user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr [$time_local] "$request" $status '
                    'rt=$request_time urt=$upstream_response_time';
    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65s;
    keepalive_requests 1000;
    client_header_timeout 10s;
    client_body_timeout 10s;
    send_timeout 30s;
    server_tokens off;

    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript;

    limit_req_zone $binary_remote_addr zone=per_ip:10m rate=100r/s;

    upstream app_backend {
        least_conn;
        server 10.0.0.10:8080 max_fails=3 fail_timeout=10s;
        server 10.0.0.11:8080 max_fails=3 fail_timeout=10s;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;
        limit_req_status 429;

        location /assets/ {
            root /var/www;
            expires 7d;
            try_files $uri =404;
        }

        location / {
            limit_req zone=per_ip burst=50 nodelay;

            proxy_pass http://app_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            proxy_connect_timeout 2s;
            proxy_read_timeout 30s;
            proxy_buffering on;
        }
    }
}

Best Practices and Common Pitfalls

  • Treat 4096, 65535, and the rate limits as starting points, not universal optimal values.

  • Do not increase worker_connections without checking memory consumption and the kernel’s somaxconn backlog.

  • Set proxy_set_header Connection "" when using upstream keepalive.

  • Trust forwarded headers and client IP headers only from known proxies; otherwise clients can spoof them.

  • Avoid unbounded request bodies, long idle timeouts, and retries for non-idempotent operations.

  • Keep TLS, certificates, configuration, and rollback artifacts synchronized with the incident runbook.

53

What is Nginx's open file limit, and why does it matter?

The open file limit is the maximum number of file descriptors one Linux process may have open, controlled by RLIMIT_NOFILE; Nginx has no single global limit because its master and worker processes have separate limits. It matters because client connections, upstream sockets, logs, cache files, and temporary files consume descriptors, and exhaustion can cause failed accepts, upstream errors, and 500 or 502 responses.

Read full answer

Applies toNginx 1.24+ on Linux

Relevant Limits

Setting Scope Meaning
RLIMIT_NOFILE Per process Maximum number of file descriptors available to a process
worker_rlimit_nofile Nginx workers Sets the workers’ RLIMIT_NOFILE value
worker_connections Per Nginx worker Maximum simultaneous connections a worker can handle; this is not itself a file-descriptor limit
fs.file-max System-wide System-wide ceiling on allocated file objects, not a per-process quota
fs.nr_open System-wide Upper ceiling permitted for RLIMIT_NOFILE values

If worker_rlimit_nofile is omitted, workers retain the limit inherited from the service manager or process that started Nginx. The descriptor limits of separate workers are independent: four workers with a limit of 65,535 do not share a single pool.

Nginx Architecture and Descriptor Usage

Nginx normally has a master process and multiple worker processes. The master reads the configuration, opens the listening sockets, and starts workers; each worker uses an event-driven architecture rather than creating a thread for every connection.

A conventional client connection normally requires one descriptor. HTTP/2 streams can share the connection’s descriptor, while a proxied request may require another descriptor for its upstream connection. Open log, cache, and temporary files also consume descriptor slots. Inherited listening and log descriptors count in each process that inherits them, so the master and every worker must all have sufficient limits.

Configuring the Limit

For a systemd-managed installation, create a service override with sudo systemctl edit nginx and set LimitNOFILE=65535 in its [Service] section. This sets the systemd soft and hard limits from which Nginx processes inherit their descriptors.

The main Nginx configuration can also contain worker_rlimit_nofile 65535;. This directive sets the workers’ RLIMIT_NOFILE; it does not create an additional descriptor pool. Align it with the systemd limit. Raising a limit above the inherited hard limit requires the necessary capability, normally CAP_SYS_RESOURCE, and should not be assumed to work.

Use this operational sequence:

  1. Run sudo systemctl daemon-reload after saving the systemd override.

  2. Run sudo nginx -t to validate the Nginx configuration.

  3. Run sudo systemctl restart nginx only after validation succeeds.

A systemd limit change is not applied to an already-running service by a reload; a controlled restart is required so the master and new workers inherit the new value.

Verification and Troubleshooting

Use ulimit -Sn and ulimit -Hn to inspect the current shell’s soft and hard limits, but do not assume the service inherited them. systemctl show nginx -p LimitNOFILE --value reports the unit’s configured limit, while /proc/$PID/limits shows the actual limit of a running Nginx process. sysctl fs.file-max and sysctl fs.nr_open show the relevant kernel ceilings.

A typical /proc/$PID/limits entry contains Max open files followed by the soft and hard values. When exhaustion occurs, Nginx may log accept() failed (24: Too many open files). Other symptoms include upstream connection failures and errors opening cache or temporary files.

Production Practices and Failure Modes

  • Size limits from measured concurrency, upstream connection use, and expected non-connection files rather than choosing a value arbitrarily.

  • Keep worker_connections and the descriptor limit aligned while considering CPU, memory, upstream capacity, and the listen backlog.

  • Remember that upstream keepalive reduces connection churn but keeps descriptors occupied.

  • Monitor descriptor usage, active connections, Nginx errors, worker restarts, and upstream failures; point-in-time /proc checks do not replace continuous monitoring.

  • During a graceful reload, old and new workers can coexist. If worker_rlimit_nofile changed, the two generations can temporarily have different limits; a full restart provides immediate consistency.

  • Back up configuration, validate with nginx -t, and use controlled reloads or restarts during maintenance and upgrades.

  • Use limit_conn, limit_req, upstream health checks, and load balancing as complementary safeguards. Increasing the limit alone does not correct excessive connection duration, upstream saturation, or an application-level descriptor leak.

54

How does Nginx serve a single-page application using client-side routing?

The standard Nginx pattern is to serve the compiled SPA files and use a history-API fallback to return index.html for client-side routes. Static assets are served directly, while /api/ requests are reverse-proxied to backend services.

Read full answer

Applies toNginx 1.24+ Open Source (HTTP/3 requires a compatible Nginx 1.25+ build with QUIC support)

How It Works

A browser request such as /dashboard reaches Nginx, but the filesystem contains only the compiled application files. Nginx uses try_files to check the requested path and then performs an internal fallback to /index.html:

try_files $uri $uri/ /index.html;

The browser loads index.html, the JavaScript router examines the URL, and the SPA renders the appropriate view without a full page reload.

Location matching follows Nginx’s rules:

  • Exact locations such as location = /index.html have the highest priority.

  • Prefix locations such as /assets/ and /api/ are selected over the general / location.

  • Regular-expression locations can take precedence over ordinary prefix locations unless ^~ is used.

  • The location / block is the final fallback for SPA routes.

Static Files, APIs, and Caching

Static assets should be served directly rather than passed through the SPA fallback. If a JavaScript bundle is missing, returning index.html produces a confusing content-type or JavaScript parsing error instead of a proper 404.

Use immutable caching only for content-hashed assets such as:

/assets/app.4f3a2b.js

The HTML entry point should normally use no-cache so browsers revalidate it and receive the latest asset references after a deployment.

The /api/ prefix keeps API traffic on the same origin as the SPA, which usually avoids browser CORS complications.

Code Example

This configuration assumes that /etc/letsencrypt/live/example.com/ contains the provisioned certificate and private key:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    default_type application/octet-stream;

    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    server_tokens off;

    gzip on;
    gzip_types
        text/plain
        text/css
        application/javascript
        application/json
        image/svg+xml;

    upstream api_backend {
        server 10.0.0.10:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl http2;
        server_name example.com;

        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;

        root /var/www/current;
        index index.html;

        add_header Strict-Transport-Security "max-age=31536000" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;

        location = /index.html {
            add_header Cache-Control "no-cache";
        }

        location /assets/ {
            try_files $uri =404;
            add_header Cache-Control "public, max-age=31536000, immutable";
        }

        location /api/ {
            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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_read_timeout 60s;
        }

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

The trailing slash on proxy_pass is significant:

Configuration Request forwarded to upstream
proxy_pass http://api_backend; /api/users remains /api/users
proxy_pass http://api_backend/; /api/users becomes /users

HTTP/2 is negotiated through TLS using ALPN. HTTP/3 is separate: it uses QUIC over UDP, typically port 443, and requires a compatible Nginx build. It should be enabled only after checking the package’s QUIC, OpenSSL, and client-support requirements.

Deployment and Upgrades

Build the application with its locked dependencies and publish an immutable release:

npm ci
npm run build

sudo install -d /var/www/releases
RELEASE="/var/www/releases/$(date -u +%Y%m%d%H%M%S)"
sudo install -d "$RELEASE"
sudo cp -a dist/. "$RELEASE/"
sudo ln -sfn "$RELEASE" /var/www/current

sudo nginx -t && sudo nginx -s reload

Adjust dist if the framework writes to another directory, such as build. The current symlink allows rollback by pointing it to the previous release.

For a configuration change, nginx -t validates syntax and references before nginx -s reload starts new workers gracefully. Existing workers finish existing connections. Monitor Nginx access and error logs, upstream latency, 502/504 responses, unusual 404 rates, certificate-expiry alerts, and the deployed asset version.

Failure Modes and Best Practices

  • Missing assets: Return 404 from the /assets/ location instead of falling back to index.html.

  • Stale HTML: Keep index.html revalidated and publish new assets before switching the application release.

  • API prefix mistakes: Remember that /api/ and /api are different paths; add an exact redirect if the API is intended to live under /api/.

  • TLS renewal: Configure certificate renewal to reload Nginx after issuing a new certificate.

  • Security headers: Add a restrictive Content Security Policy tailored to the SPA’s scripts, styles, APIs, and third-party origins.

  • Capacity: Nginx uses a master process and event-driven worker processes. Static-file serving scales efficiently, but reverse-proxy workers still need capacity for upstream connections and slow clients.

  • Observability: Preserve the original client route and upstream status in logs. For incident diagnosis, verify whether a failure is an invalid SPA route, a missing static asset, an API failure, or a TLS problem.

55

How do you reverse proxy Node.js, Python, or Ruby with Nginx?

Nginx acts as a reverse proxy, accepting public HTTP or HTTPS traffic and forwarding requests to application processes bound to a private interface or loopback address. This centralizes TLS termination, static-file serving, logging, caching, rate limiting, and load balancing while keeping application ports inaccessible from the internet.

Read full answer

Applies toNginx 1.24+ (open source)

Architecture and Routing

  • The master process reads the configuration, manages workers, and performs graceful reloads.

  • Worker processes use an event-driven, non-blocking architecture to handle many connections without one thread per request.

  • Application processes remain separate upstream services. Nginx can load-balance multiple instances of the same application.

  • A server block selects a virtual host using its address, port, and server_name.

  • Location selection generally follows this order:

  • Exact match: location = /health

  • Longest prefix match, stopping regex checks if ^~ is used

  • Regular expressions, evaluated in configuration order

  • Longest prefix match

Application Setup and Proxy Semantics

Run each application on loopback or a private network, then reference it from an upstream block:

Runtime Example process Upstream
Node.js HOST=127.0.0.1 PORT=3000 node server.js 127.0.0.1:3000
Python WSGI gunicorn --bind 127.0.0.1:8000 app:app 127.0.0.1:8000
Ruby Rack bundle exec puma --bind tcp://127.0.0.1:9292 127.0.0.1:9292

Replace server.js and app:app with the actual entry point. List additional server entries under the same upstream to distribute traffic.

proxy_pass URI handling is significant:

  • proxy_pass http://app_backend; preserves the original request URI, such as /api/users.

  • proxy_pass http://app_backend/; replaces the matched location prefix. For example, /api/users becomes /users.

  • Query parameters are preserved in both cases.

Configure the application to trust only Nginx as its forwarding proxy. Otherwise, clients can spoof X-Forwarded-For.

Production Security and Performance

  • TLS: Terminate HTTPS at Nginx using ssl_certificate, ssl_certificate_key, and ssl_protocols TLSv1.2 TLSv1.3;. Redirect port 80 to 443. Add HSTS only after confirming every subdomain supports HTTPS.

  • HTTP/2: Nginx 1.24 uses listen 443 ssl http2;. On Nginx 1.25.1+, use http2 on; with listen 443 ssl;.

  • HTTP/3: Available in Nginx 1.25+ builds with HTTP/3 support. It also requires UDP port 443, compatible clients, and correct firewall rules.

  • Static files: Serve them directly from Nginx with root, try_files, and expires; they should not consume application workers.

  • Caching: Browser caching is suitable for immutable assets. For response caching, use proxy_cache_path and proxy_cache, with explicit invalidation or short TTLs.

  • Compression: Enable gzip for text formats, but avoid recompressing images and other compressed media.

  • Rate limiting: Use limit_req_zone and limit_req. When Nginx sits behind a CDN or load balancer, configure set_real_ip_from only for trusted addresses.

  • Security headers: Add Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, and Referrer-Policy; tailor Content-Security-Policy to the application.

  • Use a dedicated WebSocket location with Upgrade and Connection headers only for WebSocket routes.

Code Example

The following complete configuration expects certificate files at the shown paths and an application listening on 127.0.0.1:3000:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr $status $request_time '
                    '$upstream_status $upstream_response_time "$http_user_agent"';
    access_log /var/log/nginx/access.log main;

    sendfile on;
    server_tokens off;

    gzip on;
    gzip_min_length 1024;
    gzip_vary on;
    gzip_types text/plain text/css application/javascript application/json image/svg+xml;

    limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;

    upstream app_backend {
        least_conn;
        server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.com;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;

        add_header Strict-Transport-Security "max-age=31536000" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;

        location /static/ {
            root /srv/example;
            expires 30d;
            access_log off;
            try_files $uri =404;
        }

        location / {
            limit_req zone=per_ip burst=20 nodelay;

            proxy_pass http://app_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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_connect_timeout 5s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
}

After creating the static directory and obtaining the certificate, install and validate the configuration:

sudo install -d -m 0755 /srv/example/static
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
sudo install -m 0644 example.com.conf /etc/nginx/nginx.conf
sudo nginx -t
sudo systemctl reload nginx

Production Operations and Best Practices

  • Monitor 502 responses for connection failures, 504 responses for upstream timeouts, 429 responses for rate limiting, and latency from $request_time and $upstream_response_time.

  • Open-source Nginx uses passive failure detection through max_fails and fail_timeout; it does not actively probe application endpoints.

  • Keep application ports blocked by host or cloud firewalls, and have the application bind to loopback or a private interface.

  • Test configuration changes with nginx -t before reloading. Reloads are graceful, allowing existing workers to finish active requests.

  • Keep a previous Nginx binary and configuration for rollback. Back up configuration and private keys securely; application data requires its own backup strategy.

  • Renew certificates automatically and reload Nginx after renewal. Monitor expiry, 5xx rates, connection counts, upstream latency, disk usage, and certificate status.

56

How does Nginx pass PHP requests to PHP-FPM?

Nginx serves static files directly and forwards PHP requests over the FastCGI protocol to a PHP-FPM process pool. A Unix domain socket is usually preferred because it avoids TCP overhead and keeps PHP-FPM off the network.

Read full answer

Applies toNginx 1.24+ and PHP-FPM 8.3 on Ubuntu 24.04

How It Works

  • The Nginx master process reads the configuration and manages worker processes.

  • Each Nginx worker uses an event-driven architecture to accept connections and route requests without one thread per connection.

  • A matching PHP request is sent through fastcgi_pass to PHP-FPM.

  • PHP-FPM’s master process manages a pool of worker processes that execute PHP scripts.

  • PHP-FPM communicates with Nginx through /run/php/php8.3-fpm.sock by default on Ubuntu.

A typical request flow is:

  1. The client requests /index.php.

  2. Nginx matches a PHP location.

  3. Nginx passes environment information and the script path to PHP-FPM.

  4. PHP-FPM executes the script and returns the response through FastCGI.

  5. Nginx sends that response to the client.

Key Configuration

  • root: Defines the directory containing the PHP application.

  • try_files: Checks whether a requested file exists before routing it to PHP.

  • fastcgi_pass: Defines the PHP-FPM socket or TCP address.

  • SCRIPT_FILENAME: Tells PHP-FPM which file to execute.

  • fastcgi_params: Supplies standard HTTP variables such as REQUEST_URI, QUERY_STRING, and REQUEST_METHOD.

Nginx checks exact location = matches first, then the longest prefix match. Regular-expression locations are evaluated in configuration order unless the prefix location uses ^~. Because the first matching regular expression wins, deny hidden-file locations should appear before the PHP expression.

For reverse proxies, URI handling differs between these forms:

Directive Result
proxy_pass http://app; Preserves the original normalized request URI
proxy_pass http://app/; Replaces the matched location prefix with /
fastcgi_pass unix:/run/php/php8.3-fpm.sock; Passes the request without adding or replacing a URI

Code Example

Install the packages, create the application directory, and deploy the virtual host:

sudo apt update
sudo apt install -y nginx php8.3-fpm

sudo install -d -o www-data -g www-data /var/www/example.com

sudo tee /etc/nginx/sites-available/example.com >/dev/null <<'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    root /var/www/example.com;
    index index.php;

    location / {
        # Route missing paths to the front controller.
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Deny dotfiles before the PHP regular expression is evaluated.
    location ~ /\. {
        deny all;
    }

    location ~* \.php$ {
        # Never execute a nonexistent PHP file.
        try_files $uri =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTP_PROXY "";

        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
    }
}
EOF

sudo ln -sfn /etc/nginx/sites-available/example.com \
  /etc/nginx/sites-enabled/example.com

sudo nginx -t
sudo systemctl enable --now nginx php8.3-fpm
sudo systemctl reload nginx

The index.php fallback supports front-controller frameworks. Remove that fallback for applications that should return a genuine 404 for unknown paths.

Production Operations

  • Test configuration changes with sudo nginx -t before reloading.

  • Inspect the complete effective configuration with sudo nginx -T.

  • Check service state with systemctl status nginx php8.3-fpm.

  • Read Nginx errors with journalctl -u nginx and PHP-FPM errors with journalctl -u php8.3-fpm.

  • Verify application routing with curl -I http://example.com and a dedicated local health endpoint.

  • Size PHP-FPM’s pm.max_children against available memory. Excess children can cause memory exhaustion and host-level OOM kills.

  • For multiple application pools, configure separate PHP-FPM sockets and load-balance between them with an Nginx upstream block.

TLS, HTTP/2, and HTTP/3 normally terminate at Nginx. The internal Nginx-to-PHP-FPM hop remains FastCGI rather than becoming HTTP/2 or HTTP/3.

Failure Modes and Security

  • 502 Bad Gateway: Usually indicates that Nginx cannot connect to the configured socket or that PHP-FPM is unavailable.

  • 403 Forbidden: May result from directory permissions, a missing index file, or Nginx access rules. A socket permission problem (13: Permission denied on the socket) shows up as 502.

  • 500 Internal Server Error: Often comes from a PHP exception, missing extension, incorrect SCRIPT_FILENAME, or exhausted PHP-FPM workers.

  • Script-not-found errors: Check SCRIPT_FILENAME, root, and whether try_files is enforcing file existence.

  • Store uploaded files outside the executable web root, or explicitly deny PHP execution in upload directories.

  • Terminate TLS at Nginx, redirect HTTP to HTTPS, and configure security headers at the edge.

  • Cache or compress only responses that are safe to cache; authenticated or personalized PHP responses generally require explicit cache rules.

Best Practices

  • Prefer a Unix socket unless PHP-FPM must run on another host.

  • Never use proxy_pass for PHP-FPM; PHP-FPM expects fastcgi_pass.

  • Do not place a broad location ~ \.php$ block without validating script existence.

  • Keep Nginx and PHP-FPM versions compatible with the application and test upgrades in staging.

  • Back up configuration before package upgrades, run nginx -t, and reload Nginx gracefully after successful validation.

57

How do you host multiple websites on a single Nginx server?

Nginx hosts multiple websites on one instance using server blocks (virtual hosts): each block binds to a listen socket and declares server_name values, and Nginx selects the block by matching the request’s Host header (or TLS SNI for HTTPS).

Read full answer

Applies toNginx 1.24+ (open source) on Linux

How It Works

  • The master process reads the configuration; worker processes handle connections through an event loop.

  • For a given IP:port, Nginx collects all server blocks listening there, then picks one by matching server_name against the request’s Host header.

  • Matching precedence: exact name; longest wildcard beginning with * (e.g. *.example.com); longest wildcard ending with * (e.g. mail.*); then regular expressions in configuration order.

  • If no name matches, the default server for that listen socket is used — the block marked default_server, otherwise the first block in configuration load order.

  • With TLS, SNI selects the certificate and server block before HTTP headers are parsed, so each site can have its own certificate on the same IP.

Configuration Layout

  • The main file /etc/nginx/nginx.conf includes site files, typically /etc/nginx/conf.d/*.conf (RHEL) or /etc/nginx/sites-enabled/* (Debian/Ubuntu).

  • Debian/Ubuntu convention: put files in sites-available/, then symlink into sites-enabled/. RHEL convention: drop .conf files directly into conf.d/.

  • One file per site keeps diffs and rollbacks clean; keep shared snippets in a separate snippets/ directory and include them.

Key Directives

  • listen 80; / listen 443 ssl; — bind address and port; add default_server to one block per port.

  • server_name example.com www.example.com; — accepts exact names, wildcards (*.example.com, .example.com), and regexes prefixed with ~.

  • root appends the full URI to the path; alias replaces the matched location prefix — mixing them is a common source of 404s.

  • try_files $uri $uri/ =404; for static sites; proxy_pass for backends.

Reverse Proxying and Load Balancing

  • proxy_pass http://backend; with no URI forwards the original request URI unchanged.

  • proxy_pass http://backend/; includes a URI of /; Nginx replaces the matched location prefix with that URI. For example, location /api/ with proxy_pass http://backend/; turns /api/foo into /foo.

  • Upstreams are defined with upstream backend { server 127.0.0.1:3000; } and referenced by name.

Common Mistakes

  • No default_server defined, so an unmatched host is served by the first block in load order (often the wrong site).

  • Editing sites-available but forgetting the symlink, or editing sites-enabled directly and losing changes on package upgrades.

  • Reloading with systemctl restart nginx instead of reload, dropping active connections.

  • Forgetting nginx -t before reload, causing a failed reload that leaves the old config running silently.

  • File permissions: the worker user (usually www-data or nginx) must read the document root.

Operational Practices

  • Validate with nginx -t, then systemctl reload nginx (graceful, no dropped connections).

  • Separate access_log and error_log per site for easier debugging and log rotation.

  • Monitor per-site 4xx/5xx rates and upstream response times via access logs or stub_status.

  • Keep TLS certificates and renewal (e.g. certbot) per server block; SNI handles selection.

Code Example

# /etc/nginx/conf.d/example.com.conf
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html;

    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

    location / {
        try_files $uri $uri/ =404;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

# Catch-all for unmatched Host headers
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 444;
}

Enable and apply:

nginx -t && systemctl reload nginx
58

How do rewrite and return differ when rewriting URLs in Nginx?

In Nginx, rewrite performs a regex-based substitution of the request URI during the rewrite phase and keeps processing the request, while return ends request processing immediately and emits a fixed response (typically a redirect or an error). rewrite is for changing where Nginx looks; return is for deciding what the client gets.

Read full answer

Applies toNginx 1.24–1.28 (mainline 1.29); config syntax valid for 1.24+

Request Processing Order

  1. Server-level rewrite directives run top-to-bottom.

  2. The location is selected by matching the (possibly rewritten) URI.

  3. Location-level rewrite directives run top-to-bottom.

  4. try_files is evaluated.

  5. The content phase runs (proxy_pass, static file, index, error_page).

A rewrite with no flag lets the remaining rewrite directives run and then searches for a location again with the new URI; last stops the current rewrite directives and starts that location search immediately; break stays inside the current location; redirect and permanent abort processing and answer the client with a 302 or 301.

rewrite vs return

Aspect rewrite return
Matching Regex (or literal prefix) against the decoded URI ($uri) No matching — unconditional
Purpose Rewrite the URI, then continue processing Send a response and stop
Status codes Not set directly; redirect → 302, permanent → 301 Any valid code: 200, 204, 301, 302, 307, 308, 400, 403, 404, 500, 444…
Redirect to another URL Only via redirect/permanent flags return 301 https://example.com$request_uri;
Body Never return 200 "okn"; sends a body
Typical use Legacy path migration, prefix stripping before proxying Canonical-host redirects, health endpoints, blocking bots, maintenance pages

Other useful facts:

  • $request_uri is the original, raw, undecoded URI including query string; $uri is the current, normalized, decoded URI. Use $request_uri when building redirect targets so query strings survive.

  • return is safe inside if — it is one of the few safe uses of the if directive. Prefer map over if when the condition is complex.

  • return 444 is an Nginx-specific “close the connection, no response” code, useful for blocking scrapers, but it looks like a client error in logs and can trigger WAF false positives.

  • For an internal redirect decided by the application, have the upstream return an X-Accel-Redirect: /internal/path response header, served by an internal location; the client never sees it.

proxy_pass and the Trailing Slash

This is the classic source of bugs, because proxy_pass may or may not contain a URI part:

proxy_pass form URI sent upstream
proxy_pass http://backend; (no URI) The (possibly rewritten) request URI is passed unchanged
proxy_pass http://backend/; (URI is /) The matched location prefix is replaced by /
proxy_pass http://backend/api/; The matched location prefix is replaced by /api/

Note also: proxy_pass with a URI part is not allowed inside if, limit_except, a named location, or a regex location. When rewrite ... break changes the URI in the same location, the URI part is ignored and the full rewritten URI is passed.

Code Example

# /etc/nginx/conf.d/example.com.conf
upstream app_backend {
    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

server {
    listen 80;
    server_name www.example.com;
    # return: unconditional, terminates processing, issues a 301 with Location
    return 301 https://example.com$request_uri;
}

server {
    # 1.24 style; from 1.25.1 prefer the separate `http2 on;` directive
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # rewrite: server-level, runs before location selection
    rewrite ^/legacy/(.*)$ /new/$1 last;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        # Strip the /api prefix; break keeps the request in this location
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://app_backend;      # no URI part -> the rewritten URI is forwarded
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location = /healthz {
        access_log off;
        return 200 "ok\n";
    }

    location = /favicon.ico {
        return 204;                          # no body, keeps probes cheap
    }
}

Validate and reload:

nginx -t && nginx -s reload
curl -sI http://localhost/new/page?q=1   # expect 301 + Location: https://example.com/new/page?q=1

Common Pitfalls and Production Notes

  • Missing break: in location /api/, rewrite ^/api/(.*)$ /$1; without break sends the rewritten URI (/users) through location matching again, so it lands in location / instead of the API location.

  • Redirect loops: rewrite ^/(.*)$ /$1 break; inside location / is a no-op that can loop with try_files fallbacks. Always test with curl -I -L --max-redirs 3.

  • 301 is cached aggressively: browsers may cache a 301 for months. Use 302 or 307 (which preserves the method) for temporary moves; 308 is the permanent, method-preserving form.

  • Rewrite regexes match $uri, so percent-encoding and // double slashes are normalised first; merge_slashes on (default) collapses them, which can break signed URLs.

  • Captures are decoded: $1 comes from the decoded URI, so test paths with encoded characters (such as %2F or spaces) before relying on the forwarded result.

  • Debugging: rewrite_log on; plus error_log /var/log/nginx/rewrite.log notice; shows each rewrite step (no debug build needed); nginx -T dumps the fully merged configuration including includes.

  • Observability: count redirects in the access log ($status 301/302) and alert on spikes — a sudden rise usually means a bad marketing link, a broken canonical rule, or an attack driving 404/301 noise.

59

Why is using if inside Nginx location blocks dangerous?

Using if inside an Nginx location is risky because it is a rewrite-phase conditional, not a general-purpose conditional block. It can create implicit nested locations, produce unexpected configuration inheritance, and turn simple rewrites into loops or inconsistent routing.

Read full answer

Applies toNginx Open Source 1.24+

Why if Is Different

Nginx uses a master process to load configuration and manage worker processes. Workers handle requests through a non-blocking event loop, but each if condition is still evaluated during request processing.

  • if belongs to the rewrite module rather than the access or content phase.

  • A server-level if runs before location selection; a location-level if runs after that location has been selected.

  • Within a location, if creates an implicit nested location. Parent location settings such as proxy_set_header, timeouts, add_header, and logging must not be assumed to behave like ordinary lexical scope.

  • The documented forms intended inside if are return and rewrite ... last; wrapping arbitrary location behavior in if is the problematic pattern.

  • Conditions use Nginx truthiness: an empty value or "0" is false, while any other non-empty value is true. There is no native else, and several if blocks can execute sequentially.

Common Failure Modes

  • Rewrite loops: rewrite ... last restarts location matching. If the same condition and rewrite remain applicable, Nginx can repeatedly re-enter the rewrite phase, produce a cycle error, or return 500.

  • Surprising break behavior: rewrite ... break stops the current rewrite sequence but continues into location processing, which is different from last.

  • Unexpected proxy behavior: Rewrites and conditional locations can change which proxy configuration applies, causing missing headers, timeouts, or a different upstream to be selected.

  • Inconsistent access control: Using if for authentication, authorization, or WAF-style decisions is fragile. These decisions belong in access-phase mechanisms such as auth_request, allow/deny, or dedicated locations.

  • Operational impact: Rewrite loops consume worker CPU and can flood logs with failures even though they do not synchronously block the entire event loop.

Matching and Directive Phases

Concern Nginx behavior Relationship to if
Location matching Exact match, longest prefix, then regex unless ^~ is used Server-level rewrites occur before this; location-level rewrites occur afterward
Rate limiting limit_req runs in the pre-access phase A rewritten URI may affect a rate-limit key that uses $uri
File checks try_files runs later than rewrite processing An if can change which file is selected
Proxy and cache proxy_pass and proxy_cache run in later content phases Rewrites can change the upstream URI or cache key
Headers and compression add_header and compression filters run later Conditional location scoping can make inherited behavior harder to reason about

TLS terminates before HTTP processing, while HTTP/2 and HTTP/3 change transport behavior rather than rewrite semantics. HTTP/3 availability also depends on the Nginx build and deployment configuration.

proxy_pass URI handling is especially important:

Configuration for location /api/ Upstream URI for request /api/v1
proxy_pass http://app; /api/v1
proxy_pass http://app/; /v1

A preceding rewrite can also change that result.

Safer Alternatives

  • Use a direct return for a fixed status or redirect.

  • Use separate exact, prefix, or regex location blocks for materially different behavior.

  • Use map to calculate a value without executing arbitrary directives.

  • Use named locations with error_page for controlled internal routing.

  • Use limit_except for simple method restrictions.

  • Use auth_request and access-phase modules for security decisions.

Code Example

This configuration is syntactically valid, but the rewrite can repeatedly select the same location when X-Debug remains present:

events {}

http {
    upstream app {
        server 10.0.0.10:8080;
    }

    server {
        listen 8080;
        server_name example.com;

        location / {
            if ($http_x_debug) {
                rewrite ^ /__debug last;
            }

            proxy_pass http://app;
        }
    }
}

A clearer design uses an explicit URI and separate locations:

upstream app {
    server 10.0.0.10:8080;
}

upstream debug_app {
    server 10.0.0.20:8080;
}

server {
    listen 8080;
    server_name example.com;

    location = /__debug {
        proxy_pass http://debug_app;
    }

    location / {
        proxy_pass http://app;
    }
}

Production Practices

  • Run nginx -t before every reload; then use nginx -s reload for a graceful reload.

  • Canary configuration changes and monitor 5xx, 499, 504, upstream status, latency, and worker CPU.

  • Log $request_uri to identify the original request and $uri to expose rewritten paths.

  • Keep security headers at stable server or location scope and use always where appropriate.

  • Treat any new if as a routing change requiring tests for redirects, caching, rate limits, headers, and upstream URI preservation.

60

What do the Nginx map and geo directives do?

The Nginx map directive creates a variable by matching values from another variable, while geo creates a variable by matching a client IP address. Both provide configurable lookup tables for routing, access control, logging, caching, and request handling.

Read full answer

Applies toNginx 1.24+ on Ubuntu 22.04/24.04

Core Difference

Directive Input Typical uses
map Any Nginx variable, such as a header, URI, method, or cookie Header normalization, protocol selection, tenant routing, request classification
geo Client IP address, $remote_addr by default Private-network detection, regional routing, coarse access policies
Both Defined in the http context Produce a variable that can be referenced elsewhere in the configuration

Neither directive performs a request by itself. They generate values that other directives use.

Matching Behavior

  • map matching:

  • Exact string matches take precedence.

  • With the hostnames parameter, the longest matching prefix or suffix mask (such as *.example.com) is selected next.

  • Regular expressions are evaluated in configuration order.

  • Use ~ for case-sensitive matching and ~* for case-insensitive matching.

  • The default entry handles unmatched input.

  • geo matching:

  • Matches exact addresses, address ranges, and CIDR networks.

  • IPv4 and IPv6 are supported in modern Nginx versions.

  • default should explicitly define the result when no address matches.

  • By default, the source is $remote_addr; an alternate address variable can be supplied when necessary.

  • Undefined results: If no entry matches and no default is configured, the resulting variable is generally empty, which can cause unexpected headers, routing, or access decisions.

Configuration Example

This complete configuration demonstrates both directives. The map validates and propagates a request ID, while geo classifies the client network.

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    # Select a safe correlation ID from an untrusted header.
    map $http_x_request_id $correlation_id {
        default $request_id;
        "~^[A-Za-z0-9._-]{1,64}$" $http_x_request_id;
    }

    # Support WebSocket upgrades and close other connections normally.
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    # Classify the direct client address.
    geo $client_network {
        default public;
        10.0.0.0/8 private;
        127.0.0.0/8 loopback;
        172.16.0.0/12 private;
        192.168.0.0/16 private;
        ::1/128 loopback;
        fc00::/7 private;
    }

    log_format main '$remote_addr $status $correlation_id $client_network';
    access_log /var/log/nginx/access.log main;

    upstream app_backend {
        server 10.0.0.10:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header X-Correlation-ID $correlation_id;
            proxy_set_header X-Client-Network $client_network;
            proxy_pass http://app_backend;
        }
    }
}

After merging the configuration into /etc/nginx/nginx.conf, validate and deploy it with:

sudo nginx -t
sudo systemctl reload nginx

How It Works

Nginx’s master process reads the configuration and manages worker processes. Each worker uses an event-driven event loop to handle connections without dedicating a thread to every request.

During configuration parsing, map and geo build lookup structures that workers inherit from the master. When a request references the resulting variable, Nginx performs the corresponding lookup and uses the value in headers, logs, proxy settings, caching decisions, or other supported contexts.

Variable evaluation is generally lazy and cached for the request. Consequently, a map or geo declaration has little effect unless its variable is actually referenced. Regular-expression evaluation and complex lookup tables should still be monitored because they contribute to per-request processing.

Production Practices

  • Validate before reload: Always run nginx -t; a reload applies configuration changes gracefully, while a restart interrupts active connections.

  • Treat headers as untrusted: Do not allow arbitrary header values to select sensitive backends or bypass policy. Validate and allowlist them, as the correlation-ID map does.

  • Account for trusted proxies: geo normally sees the address of the immediate TCP peer. Behind a load balancer, configure Nginx’s realip module with set_real_ip_from and real_ip_header, trusting only known proxy addresses.

  • Avoid geo as a country database: For country-level GeoIP data, use the GeoIP2 module and an appropriately licensed database.

  • Observe behavior: Log the generated classifications and track status codes, upstream errors, latency, and connection reuse. stub_status and access logs provide useful signals.

  • Manage changes safely: Keep configuration in version control, retain a rollback copy, and test upgrades with the deployed Nginx binary. nginx -T dumps the complete active configuration during troubleshooting.

61

How do you define and use variables in Nginx configuration?

Nginx variables let configuration directives reuse request data, computed values, or mapped values. They are defined with directives such as set and map, then referenced using the $name syntax.

Read full answer

Applies toNginx Open Source 1.24+

Core Syntax and Variable Sources

Variables use $name or ${name} syntax. Not every directive supports variables; only directives implemented with variable expansion can use them.

Source Example Behavior
set set $route_name "api-v1"; Assigns a value during the rewrite phase
map map $http_x_environment $env { ... } Converts one value into another using explicit matches
Request header $http_x_trace_id Reads a request header such as X-Trace-Id
Query argument $arg_page Reads a query-string argument such as ?page=2
Cookie $cookie_session_id Reads a request cookie
Built-in URI values $uri, $request_uri, $args Expose normalized URI, original URI, and query string

map belongs in the http context:

map $http_x_environment $deployment_env {
    default   production;
    staging   staging;
    canary    canary;
}

Matching uses these rules:

  1. Exact string matches take precedence.

  2. With the hostnames parameter, the longest matching wildcard mask (such as *.example.com) wins.

  3. Regular expressions are evaluated in configuration order; use ~ for case-sensitive and ~* for case-insensitive matching.

  4. default handles unmatched requests.

Evaluation Model and Scope

The Nginx master process reads and validates the configuration, while worker processes handle requests using an event-driven architecture. A variable definition belongs to the loaded configuration, but request-time values are evaluated in each worker’s request context; workers do not share mutable request-variable values. Some built-in variables, such as $pid, are process-scoped.

set runs during request rewrite processing. Consequently, a variable assigned in location /api/ is available to later directives such as proxy_set_header and add_header:

set $route_name "api-v1";
proxy_set_header X-Route-Name $route_name;

map is evaluated lazily and normally cached for the request. If its source can change during request processing, the volatile map parameter can disable that caching; this is mainly relevant to variables derived from upstream responses.

Nginx variables are not shell variables or environment-variable substitutions. The env directive passes an environment variable to worker processes, but it does not automatically create a corresponding Nginx variable.

Production Usage

Variables are especially useful for operational configuration:

  • Reverse proxying: Build forwarding headers with $host, $remote_addr, $scheme, and $proxy_add_x_forwarded_for.

  • Load balancing: Keep servers in an upstream block while using variables for metadata, logging, and request headers.

  • Static files: Use $uri with try_files to perform normalized URI lookup.

  • Caching and rate limiting: Include selected request attributes in proxy_cache_key or limit_req_zone keys.

  • Security headers: Populate response headers with validated values, such as a mapped environment or request identifier.

  • Logging: Record $status, $request_time, $upstream_status, and $upstream_response_time for incident analysis.

  • Protocol handling: Variable behavior is broadly consistent across HTTP/1.1 and HTTP/2, and across HTTP/3 on versions that support it; when Nginx terminates TLS, it still does so at Nginx.

Treat client-supplied headers as untrusted. Map them to known values before placing them in proxy or response headers, and avoid exposing sensitive values in logs.

Code Example

This complete configuration demonstrates map, set, static-file handling, reverse proxying, and an upstream:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    # Only explicitly approved environment names are forwarded.
    map $http_x_environment $deployment_env {
        default  production;
        staging  staging;
        canary   canary;
    }

    upstream api_backend {
        server 10.0.0.10:8080;
        keepalive 32;
    }

    server {
        listen 8080;
        server_name example.com;

        root /var/www/html;

        # Serve an existing static file or return 404.
        location / {
            try_files $uri $uri/ =404;
        }

        location /api/ {
            set $route_name "api-v1";

            # Preserve the original /api/... URI and use upstream keepalive.
            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";

            proxy_set_header Host $host;
            proxy_set_header X-Deployment-Env $deployment_env;
            proxy_set_header X-Route-Name $route_name;

            add_header X-Route-Name $route_name always;
        }
    }
}

This is a complete main configuration. Save it as the active Nginx configuration before reloading, or merge its http-level and server blocks into the existing configuration without creating a nested http context. Then validate and perform a graceful reload:

sudo nginx -t
sudo nginx -T
sudo nginx -s reload

curl -i \
  -H 'Host: example.com' \
  -H 'X-Environment: staging' \
  http://127.0.0.1:8080/api/health

Common Pitfalls and Best Practices

  • Trailing slash changes URI replacement: With location /api/ and proxy_pass http://api_backend;, the backend receives /api/users. With proxy_pass http://api_backend/, the matching /api/ prefix is replaced by /, producing /users.

  • Dynamic proxy hosts need care: A domain name constructed in proxy_pass may require a configured resolver; prefer a static upstream block for predictable DNS behavior.

  • Missing values are often empty strings: Check the source header or argument and validate it rather than assuming it exists.

  • Do not misuse if: The rewrite module’s if has surprising inheritance behavior. Prefer map, try_files, or explicit location matching; reserve if mainly for safe operations such as return.

  • Variables do not protect secrets: Values can be exposed in configuration files, worker memory, or logs. Store credentials in protected files or a secrets system, not directly in variables.

  • Test before reloading: Run nginx -t, verify behavior with curl, monitor error and upstream logs, and keep configuration under version control with staged upgrades.

62

How to serve content based on request header in Nginx?

Use Nginx’s map directive to translate a request header into a safe variable, then use that variable in root, alias, or another location-specific setting.

Read full answer

Applies toNginx 1.24+ (open source)

How It Works

  • Nginx exposes request headers as variables named $http_<header_name>, with hyphens converted to underscores and names lowercased. For example, X-Content-Variant becomes $http_x_content_variant.

  • The map directive belongs in the http context and creates a new variable whose value depends on another variable.

  • Map keys can be exact strings, regular expressions, or a default fallback. Missing headers evaluate to an empty string, so default handles that case.

  • The resulting variable can be used in root, alias, try_files, or other directives. This avoids if, which is error-prone in Nginx location processing.

  • If responses differ by request header, send a Vary header so caches do not reuse the wrong variant.

Configuration Example

http {
    map $http_x_content_variant $variant_root {
        default   /var/www/default;
        "beta"    /var/www/beta;
        "~^canary-" /var/www/canary;
    }

    server {
        listen 80;
        server_name example.com;

        root $variant_root;

        location / {
            try_files $uri $uri/ =404;
        }

        add_header Vary "X-Content-Variant" always;
    }
}

Validate before reloading:

nginx -t
nginx -s reload

Common Pitfalls

  • Do not use the raw header directly in root or alias; a malicious or malformed header could influence filesystem paths. Whitelist values in map instead.

  • Remember that header names are normalized: X-API-Version maps to $http_x_api_version, not $http_X_API_Version.

  • An absent header is an empty string, not null; always define default.

  • map must be in the http context, not inside server or location.

  • If Nginx caches or proxies the response, include the header in the cache key or send Vary, otherwise clients may receive the wrong variant.

Best Practices

  • Use exact or tightly constrained regex keys rather than broad patterns.

  • Keep all possible roots under one controlled parent directory.

  • Add Vary for any header that changes the response body or selected file.

  • For proxied upstreams, include the header in proxy_cache_key when caching is enabled.

  • Test with curl -H 'X-Content-Variant: beta' http://example.com/ and inspect both status code and selected file.

63

How can Nginx serve cross-origin API requests with CORS headers?

Nginx can enforce CORS at the edge by selecting allowed origins, returning the required response headers, and answering browser preflight requests without forwarding them to the application. This keeps CORS policy centralized and ensures preflight failures also include the appropriate headers.

Read full answer

Applies toNginx OSS 1.24+

How It Works

  • Nginx uses a master process to manage worker processes; workers use an event-driven loop to handle connections without dedicating a thread to every request.

  • A CORS simple request is sent to the upstream normally, and Nginx adds headers to the response.

  • A CORS preflight request is an OPTIONS request containing Origin and Access-Control-Request-Method. Nginx should handle it directly with a 204 No Content response.

  • Use an allowlist of exact origins rather than reflecting arbitrary Origin values. An unrecognized origin receives no Access-Control-Allow-Origin header, so the browser blocks the response.

  • Put the policy in the location handling the relevant API or static assets. Nginx location matching uses exact matches first, then the longest matching prefix, then regular-expression locations in their configured order.

Configuration Behavior

  • add_header adds headers to successful and error responses when always is specified.

  • add_header directives are inherited only when the child context has no add_header directives of its own. If a nested location defines another header, repeat or include the CORS headers there.

  • Access-Control-Allow-Credentials: true is needed for browser requests that include cookies or other credentials.

  • Credentialed CORS cannot use Access-Control-Allow-Origin: *; the response must contain one specific allowed origin.

  • Vary: Origin is important when the allowed origin varies, because caches must not reuse a response with the wrong CORS policy.

  • CORS is a browser security mechanism, not authentication or server-side authorization. Protect APIs with normal authentication and authorization controls, and use CSRF protection for cookie-authenticated state-changing requests.

Production and Failure Modes

Situation Recommended behavior
Public, unauthenticated API A fixed origin or * can be used when credentials are not enabled
Credentialed browser API Allowlist exact origins and return Access-Control-Allow-Credentials: true
Multiple environments Use separate server blocks or maps for development, staging, and production
Upstream already sets CORS headers Avoid duplicate headers; choose one layer to own the CORS policy
Preflight returns 405 or reaches the upstream Handle OPTIONS in Nginx and return 204
Proxy or upstream returns 4xx/5xx Keep always so browsers can inspect the response
Shared caching or a CDN is used Ensure Vary: Origin is preserved and the CDN honors it

TLS, HTTP/2, HTTP/3, compression, and caching do not change the CORS rules, but they are commonly deployed on the same Nginx server. Apply security headers at the appropriate TLS context, and be aware that adding add_header in a nested location can interrupt inheritance.

Code Example

The following is a complete example configuration. It uses HTTP so it is self-contained; in production, place the same location in the HTTPS server block with valid certificate paths.

worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    access_log /var/log/nginx/access.log;

    # Only allow explicitly trusted browser origins.
    map $http_origin $cors_origin {
        default "";
        "https://app.example.com" $http_origin;
        "https://admin.example.com" $http_origin;
    }

    upstream api_backend {
        server 10.0.0.10:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name api.example.com;

        location /api/ {
            # Headers are also included on errors because of "always".
            add_header Access-Control-Allow-Origin $cors_origin always;
            add_header Access-Control-Allow-Credentials "true" always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Request-ID" always;
            add_header Access-Control-Max-Age 86400 always;
            add_header Vary "Origin" always;

            # Answer preflight requests at Nginx.
            if ($request_method = OPTIONS) {
                return 204;
            }

            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # No trailing slash preserves the original /api/... URI.
            proxy_pass http://api_backend;
        }
    }
}

With location /api/ and proxy_pass http://api_backend;, the original URI, such as /api/orders, is passed to the upstream unchanged. Using proxy_pass http://api_backend/; instead replaces the matched /api/ prefix with /.

Validation and Operations

  1. Validate the configuration before reloading:

bash sudo nginx -t sudo nginx -s reload

  1. Test a preflight request:

bash curl -i -X OPTIONS http://api.example.com/api/orders \ -H 'Origin: https://app.example.com' \ -H 'Access-Control-Request-Method: POST' \ -H 'Access-Control-Request-Headers: Authorization, Content-Type'

  1. Monitor OPTIONS responses, 4xx/5xx rates, upstream latency, and rejected origins in the access log. Do not log authorization headers or cookies.

  2. Keep a configuration backup, test upgrades in staging, and use a graceful reload so existing worker processes finish their current requests.

  3. If rate limiting is applied to preflight requests, verify that rejected requests still receive the CORS headers; otherwise the browser may report only a generic CORS error.

64

How does Nginx mitigate Slowloris attacks?

Slowloris is a denial-of-service attack in which an attacker opens many connections and sends HTTP headers extremely slowly, exhausting server resources. Nginx mitigates it primarily with its event-driven worker architecture, strict client timeouts, connection limits, and request-rate controls.

Read full answer

Applies toNginx 1.24+ on Linux

How It Works

Nginx uses a master process to manage configuration and worker processes. Each worker runs an event loop that handles many connections without blocking on slow clients. A Slowloris attacker can therefore consume memory and connection slots, but cannot force one worker to synchronously wait for every slow client.

The most important timeout is client_header_timeout:

  • Header timeout: client_header_timeout 10s terminates a request whose client cannot send the request header within the configured period.

  • Body timeout: client_body_timeout 10s applies while reading the request body.

  • Response timeout: send_timeout 10s limits the time between writes to a slow client.

  • Idle keepalive timeout: keepalive_timeout 15s closes idle persistent connections.

  • Keepalive request limit: keepalive_requests 1000 prevents a client from using one connection indefinitely for many requests.

These timeouts are generally inactivity timeouts between successive reads or writes, not one absolute deadline for the entire request. An attacker who continuously sends a small amount of data may therefore require additional connection or edge-level controls.

Defensive Configuration

The following configuration demonstrates the main defenses. Place it in an http context, such as /etc/nginx/conf.d/slowloris-protection.conf on distributions that include that directory from nginx.conf.

# Connection and request limits by client address
limit_conn_zone $binary_remote_addr zone=per_ip_connections:10m;
limit_req_zone $binary_remote_addr zone=per_ip_requests:10m rate=20r/s;

# Include request duration and size in access logs
log_format slowloris
    '$remote_addr "$request" status=$status '
    'request_time=$request_time request_length=$request_length';

server {
    listen 80 backlog=4096;
    server_name example.com;

    # Protect the connection and request-reading paths
    client_header_timeout 10s;
    client_body_timeout 10s;
    send_timeout 10s;
    keepalive_timeout 15s;
    keepalive_requests 1000;
    reset_timedout_connection on;

    # Additional limits against connection and request floods
    limit_conn per_ip_connections 20;
    limit_req zone=per_ip_requests burst=40 nodelay;
    limit_req_status 429;
    limit_conn_status 429;

    access_log /var/log/nginx/access.log slowloris;

    location / {
        proxy_pass http://app_backend;
        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 "";
    }
}

upstream app_backend {
    server 10.0.0.10:8080;
    keepalive 32;
}

limit_req primarily protects against high request rates once requests are parsed; it is not a complete defense against clients that never finish sending headers. limit_conn reduces concurrent connection pressure, but the thresholds must be tuned carefully because many users may share one NAT address.

Production and Security Considerations

  • Use an edge layer: A cloud load balancer, CDN, or WAF should enforce connection limits, request timeouts, and preferably an absolute request deadline before traffic reaches Nginx.

  • Protect TLS handshakes: On Nginx 1.25.3+, set ssl_handshake_timeout 10s for TLS listeners so clients cannot hold connections open during a handshake (the default is 60s); on 1.24, client_header_timeout also covers the handshake.

  • Account for HTTP/2: HTTP/2 multiplexes streams over one connection, so connection-based limits are less granular. Use request limits and enforce concurrent-stream limits at the TLS terminator.

  • Review HTTP/3 exposure: HTTP/3 uses QUIC and has its own connection and handshake behavior. Keep it behind the same edge controls and do not expose an unprotected UDP listener directly to untrusted traffic.

  • Do not confuse upstream timeouts: proxy_read_timeout controls how long Nginx waits for an upstream response; it does not protect against a slow client sending request headers.

  • Tune for legitimate clients: Very low timeouts can affect mobile networks, large uploads, or slow integrations. Measure normal request rates and upload behavior before tightening limits.

  • Protect secrets and logs: Use TLS certificates through a secrets or certificate-management process, and avoid logging authorization headers or sensitive request bodies.

Operational Monitoring and Validation

After changing the configuration, validate it before reloading:

sudo nginx -t
sudo systemctl reload nginx

If the test fails, use sudo nginx -T to inspect the complete active configuration and sudo nginx -V to verify the Nginx version and compiled modules. Monitor access logs for:

  • Increased 408 responses, indicating client-header or body timeouts.

  • Large values of $request_time, indicating slow requests.

  • Large $request_length values combined with long durations.

  • Rising active connections, file-descriptor usage, 502/504 responses, or worker CPU saturation.

During an incident, inspect socket and worker state with commands such as ss -s, systemctl status nginx, and the Nginx error log. A graceful reload preserves existing connections, but an overloaded host may require the edge layer to shed traffic while limits and timeouts are adjusted.

65

How do you configure Nginx stream load balancing for TCP and UDP?

Nginx stream load balancing proxies Layer 4 TCP connections or UDP datagram sessions to multiple upstream servers. It operates independently of Nginx’s HTTP module and selects upstreams using methods such as round-robin or least-connections.

Read full answer

Applies toNGINX OSS 1.24+ compiled with the stream module

Architecture and Configuration

Nginx uses a master process to read configuration and manage worker processes. Workers use an event-driven loop to accept and proxy traffic, so a worker can manage many connections without dedicating a thread or process to each one.

The stream block is separate from http:

  • server blocks match traffic by listening address and port, not HTTP paths.

  • upstream blocks define backend servers and the balancing policy.

  • proxy_pass connects the listening socket to an upstream.

  • zone stores shared upstream state in shared memory.

  • worker_connections must account for both client-side and upstream-side sockets.

TCP and UDP Behavior

Characteristic TCP UDP
Unit proxied Connection Datagram session
Default balancing Round-robin Round-robin
Useful policy least_conn for uneven connection durations Usually round-robin or consistent hashing
Failure handling New connections can select another healthy peer No application-level retry; clients must retry
Timeout meaning Inactivity between reads or writes Inactivity between datagram exchanges

For TCP, each new client connection is assigned an upstream, and existing connections remain attached to that upstream. max_fails and fail_timeout provide passive failure handling: after the configured failures within the interval, that peer is temporarily excluded.

For UDP, there is no connection handshake or request/response guarantee. Nginx cannot determine application health, retry every datagram safely, or balance individual DNS queries independently of the client session.

Unlike HTTP, proxy_pass in the stream module has no URI path or trailing-slash rewriting behavior. Use proxy_pass upstream_name; or proxy_pass 10.0.0.10:5432;; HTTP-style forms such as proxy_pass upstream_name/; are invalid.

Code Example

worker_processes auto;

events {
    worker_connections 4096;
}

stream {
    log_format tcp_balancer
        '$remote_addr:$remote_port [$time_local] '
        '$status session=$session_time upstream=$upstream_addr '
        'connect=$upstream_connect_time '
        'received=$upstream_bytes_received sent=$upstream_bytes_sent';

    access_log /var/log/nginx/stream-access.log tcp_balancer;

    upstream postgres_tcp {
        zone postgres_tcp 64k;
        least_conn;

        server 10.0.0.10:5432 max_fails=3 fail_timeout=10s;
        server 10.0.0.11:5432 max_fails=3 fail_timeout=10s;
    }

    upstream dns_udp {
        zone dns_udp 64k;

        server 10.0.0.20:53 max_fails=3 fail_timeout=10s;
        server 10.0.0.21:53 max_fails=3 fail_timeout=10s;
    }

    server {
        listen 127.0.0.1:3306;

        allow 127.0.0.1;
        allow 10.0.0.0/16;
        deny all;

        proxy_pass postgres_tcp;
        proxy_connect_timeout 2s;
        proxy_timeout 30s;
    }

    server {
        listen 127.0.0.1:5353 udp;

        allow 127.0.0.1;
        allow 10.0.0.0/16;
        deny all;

        proxy_pass dns_udp;
        proxy_connect_timeout 2s;
        proxy_timeout 5s;
    }
}

Validate and activate the configuration:

sudo nginx -t
sudo systemctl reload nginx

nc -vz 127.0.0.1 3306
dig @127.0.0.1 -p 5353 example.com A +time=1 +tries=1

Confirm that the build includes stream support with nginx -V 2>&1 | grep -- '--with-stream'. A successful nginx -t is the authoritative check for the installed configuration.

Production Operations

  • Monitoring: Export or collect stream logs and alert on upstream connection failures, timeouts, resets, session duration, and backend saturation. NGINX Plus and suitable exporters can provide additional metrics.

  • Capacity: Monitor active connections, worker CPU, socket limits, and backend health. proxy_connect_timeout limits backend connection establishment; proxy_timeout limits inactivity and does not impose a total session duration.

  • Upgrades: Keep configuration under version control, test it with nginx -t, canary changes, and use a graceful reload so existing TCP sessions can finish.

  • Backups: Back up /etc/nginx and deployment artifacts. The stream configuration is not a durable data store, but keeping upstream inventories and rollback files is operationally important.

  • Incidents: Check ss -lntup, the stream access log, Nginx error log, firewall rules, and direct backend connectivity. Static upstream addresses require configuration updates when backend IPs change.

Security and Common Pitfalls

The stream module does not inspect HTTP, so HTTP headers, authentication, caching, compression, and application-level rate limits do not apply. It can pass TLS through unchanged, but TLS termination requires additional certificate-handling configuration.

Restrict listeners with allow/deny rules and host firewalls, especially for DNS or other UDP services that could become open proxies or reflection sources. OSS stream uses passive health checks; NGINX Plus provides active upstream health checks.

HTTP/2 over TCP can be proxied because the stream module is protocol-agnostic. HTTP/3 uses QUIC over UDP and requires QUIC-aware handling rather than being treated as an ordinary UDP workload.

66

What distinguishes Nginx Plus from open-source Nginx?

NGINX Plus is the commercial, subscription-based edition of NGINX, built on the open-source NGINX core and augmented with enterprise capabilities such as active health checks, live API-driven configuration, JWT authentication, and vendor support. Open-source NGINX provides the same fundamental web-server and reverse-proxy architecture at no license cost.

Read full answer

Applies toopen-source NGINX 1.24+ and current supported NGINX Plus releases

Core Architecture

Both editions use NGINX’s event-driven, master-and-worker architecture:

  • The master process reads the configuration, manages workers, performs reloads, and coordinates graceful shutdown.

  • worker processes accept connections and process requests through an event loop, allowing each worker to handle many connections efficiently.

  • Separate cache manager and cache loader processes support the shared file cache.

  • Additional modules and management APIs distinguish Plus, but the underlying request-processing model remains the same.

Plus does not automatically provide dramatically higher performance. Its advantages come mainly from additional capabilities, commercial integration, testing, and support rather than a fundamentally different server architecture.

Feature Comparison

Capability Open-source NGINX NGINX Plus
Static files, reverse proxy, TLS, caching, compression Supported Supported
HTTP/2 and HTTP/3 Supported in suitable modern builds and environments Supported in vendor-tested builds and environments
Passive upstream health checks Supported through max_fails and fail_timeout Includes passive checks plus active health checks using directives such as health_check
Dynamic configuration Normally requires nginx -t followed by nginx -s reload Includes a write API for controlled runtime changes to supported settings, including upstream membership and weights
Session persistence Requires hash-based routing or external solutions Includes native sticky-cookie and related persistence options
JWT validation Usually requires an external service or auth_request integration Provides the native auth_jwt module
Rate limiting Provides limit_req_zone and limit_req Includes the same base mechanism; advanced policy management is typically handled through the Plus API or external tooling
Metrics stub_status, logs, and third-party exporters Detailed metrics API and entitlement-dependent commercial monitoring and management
Support Community support or separate commercial support agreements Vendor support, security updates, compatibility testing, and an SLA
License Free under the open-source license Paid per-host subscription with additional licensed modules

Plus-specific directives such as health_check, api, and auth_jwt are not understood by an open-source NGINX binary; attempting to load them there causes nginx -t to fail.

Configuration Compatibility

Both products use the same http, server, location, and upstream hierarchy. Server selection is based on listen, address, and server_name; location selection considers exact matches, the longest matching prefix, and regular expressions in configuration order.

Important proxy behavior is identical:

  • proxy_pass http://backend; forwards the original request URI.

  • proxy_pass http://backend/; replaces the matched location prefix with /.

  • With location /api/, /api/users becomes /users for the trailing-slash form but remains /api/users for the form without one.

Standard configurations are generally portable between editions, provided they do not use Plus-only directives. In both cases, validate changes with nginx -t before reloading with nginx -s reload.

Security and Operational Trade-offs

NGINX Plus is not itself a full enterprise WAF. Products such as NGINX App Protect WAF and API security capabilities are separately licensed add-ons. TLS termination, secure headers, request filtering, and basic authentication can be implemented in both editions, but configuration quality and application-layer protections still determine the actual security posture.

In production:

  • Monitor upstream latency, error rates, active connections, worker saturation, health-check failures, disk usage, and certificate expiry.

  • Treat the Plus API as a privileged control plane: restrict access by network policy and credentials, and audit changes.

  • Keep dynamic Plus API changes in a declarative source of truth such as an infrastructure repository; runtime API changes may not survive a restart or reload.

  • Back up nginx.conf, included files, TLS certificates, and integration definitions before upgrades.

  • Upgrade the entire binary and compatible dynamic modules together, run nginx -t, and reload gracefully to avoid dropping active connections.

Active health checks and JWT validation create additional upstream or identity-service traffic, so capacity and failure behavior should be tested under realistic conditions.

When to Choose

Open-source NGINX is usually the better fit for conventional static hosting, reverse proxying, caching, and load balancing when the team wants to avoid licensing costs and can manage integrations and support directly.

NGINX Plus is more compelling when requirements include active health checks, native JWT validation, runtime reconfiguration, session persistence, enterprise monitoring, or a vendor-backed support agreement. Organizations should compare those benefits against subscription cost and operational complexity rather than assuming Plus provides better performance in every workload.

67

What is the OpenResty distribution of Nginx?

OpenResty is an Open Source distribution of Nginx that combines the Nginx core with the ngx_lua module, LuaJIT, and supporting Lua libraries. It turns Nginx’s event-driven server into a programmable application platform for API gateways, authentication, authorization, request transformation, and other edge logic.

Read full answer

Applies toOpenResty 1.27.1.2 (bundled Nginx 1.27.1 and LuaJIT 2.1)

Architecture

OpenResty retains Nginx’s multi-process architecture:

  • The master process reads the configuration, manages workers, and coordinates graceful shutdowns and binary upgrades.

  • Worker processes accept connections and process requests concurrently.

  • Each worker uses an event loop, allowing it to manage many connections efficiently without allocating a thread per connection.

  • ngx_lua executes Lua callbacks inside the worker handling the request. LuaJIT implements Lua 5.1 semantics with substantial performance-oriented extensions.

This design is effective for I/O-heavy workloads, but it also creates an important constraint: blocking Lua code stalls the worker and the requests assigned to it. Production handlers should therefore avoid blocking filesystem operations, synchronous network calls, and os.execute, favoring APIs such as cosockets and timers for asynchronous work.

Lua Capabilities

OpenResty adds programmable hooks at several request phases:

  • access_by_lua_block: authentication, authorization, and request rejection.

  • rewrite_by_lua_block: URL inspection, routing, and request transformation.

  • content_by_lua_block: custom response generation or orchestration.

  • body_filter_by_lua_block: response-body modification.

  • log_by_lua_block: structured logging and metrics.

The distribution also includes modules and libraries for cosockets, timers, subrequests, locks, shared dictionaries, DNS resolution, Redis, MySQL, and stream integration. These facilities make OpenResty suitable for high-throughput edge processing without moving every small operation into a separate service.

Nginx Features and Configuration Model

OpenResty retains Nginx’s normal configuration hierarchy of http, server, and location blocks. Within a selected server, an exact location match (=) wins immediately; otherwise, Nginx evaluates regular-expression locations in configuration order and otherwise uses the longest matching prefix, with ^~ preventing regex evaluation for that prefix.

It supports static-file serving, reverse proxying, upstream load balancing, TLS, HTTP/2, caching, compression, rate limiting, security headers, and access logging. HTTP/3 support depends on the bundled build and the client-facing UDP/QUIC path, so operators must verify it explicitly rather than assume it is enabled.

Lua directives can be placed in the relevant server or location contexts and execute during the corresponding Nginx request phases. This allows programmable behavior without replacing the surrounding proxy, cache, or load-balancing functionality.

Comparison

Approach Strengths Main trade-offs
Stock Nginx Efficient static delivery, proxying, and HTTP/2 without a scripting runtime Custom request logic normally requires external services or modules
OpenResty Low-latency programmable request handling within Nginx workers Requires disciplined non-blocking Lua code and careful worker isolation
Separate application service Rich language ecosystem, mature application frameworks, and independent scaling Additional network hops, serialization overhead, and more distributed failure modes

Production and Security Guidance

  • Treat Nginx access logs, Lua logs, metrics, and traces as separate operational signals. Monitor upstream latency, status rates, request timeouts, worker saturation, Lua exceptions, and custom upstream-health state.

  • Validate headers, query parameters, paths, and request bodies before using them in routing, authorization, or logging.

  • Do not trust X-Forwarded-* headers unless a controlled upstream proxy overwrites them.

  • Apply TLS, request and connection limits, rate limiting, and appropriate security headers at the edge.

  • Validate every configuration change before reload. nginx -t checks Nginx configuration syntax but does not execute every Lua callback, so Lua behavior also needs automated testing.

  • Keep configuration, Lua source, and deployment artifacts in version control, while storing private keys in a secrets manager or other protected key store.

  • Back up configuration and certificates according to the deployment policy, retain a known-good release for rollback, and monitor old workers after a graceful reload until they finish draining requests.

  • OpenResty has no built-in circuit breaker; implement and monitor one explicitly in Lua or the surrounding platform if upstream failure isolation is required.

68

How does Nginx function as a Kubernetes ingress controller?

Nginx works as a Kubernetes ingress controller by running Nginx as the data plane while a controller process watches Kubernetes API objects and translates Ingress, Service, Endpoint, and Secret changes into Nginx configuration, then reloads Nginx to apply routing, TLS, and load balancing.

Read full answer

Applies toingress-nginx 1.10+ on Kubernetes 1.28+; the same watch-and-reload model also applies to NGINX Ingress Controller 3.x, though annotations and dynamic-update features differ.

How It Works

  • The controller runs as a Deployment, usually in the ingress-nginx namespace, with one or more replicas for high availability.

  • It watches Ingress, Service, Endpoints/EndpointSlice, and Secret resources across namespaces.

  • When an object changes, it regenerates Nginx configuration from templates and applies it with an Nginx reload.

  • Nginx then routes external traffic to backend Pods using the current Endpoint list, so Pod IP changes are reflected after the next configuration update.

  • A validating admission webhook can reject invalid Ingress objects before they reach the cluster state.

Request Path

  • Client DNS resolves to the controller’s external address, usually a cloud LoadBalancer Service or NodePort.

  • Traffic enters a controller Pod, where Nginx selects a server block by Host and a location by path.

  • Nginx proxies the request to one of the backend Pod IPs returned by the Kubernetes Service’s endpoints.

  • TLS termination normally happens at Nginx using a certificate stored in a Kubernetes Secret referenced by the Ingress.

Configuration and Annotations

  • Use spec.ingressClassName: nginx rather than the deprecated kubernetes.io/ingress.class annotation.

  • ingress-nginx exposes many behaviors through annotations, such as nginx.ingress.kubernetes.io/rewrite-target, proxy-body-size, ssl-redirect, and configuration-snippet.

  • Global tuning is usually done through the ingress-nginx ConfigMap, for example timeouts, HSTS, and proxy buffer sizes.

  • Path matching follows Nginx location rules, so prefix, exact, and regex paths can interact in ways that surprise users.

Production Considerations

  • Run at least two controller replicas behind a PodDisruptionBudget and spread them across nodes or zones.

  • Set CPU and memory requests/limits; Nginx is efficient, but reload storms and large configurations can spike resource use.

  • Enable metrics and dashboards for request rate, latency, 5xx rate, and controller reload errors.

  • Keep controller and Kubernetes versions compatible, and test upgrades in staging because annotation behavior can change.

  • Avoid putting sensitive logic in configuration-snippet unless it is reviewed, since it injects raw Nginx directives.

Troubleshooting

  • Check Ingress status and events with kubectl describe ingress <name>.

  • Inspect controller logs with kubectl logs -n ingress-nginx deploy/ingress-nginx-controller.

  • Validate generated configuration with kubectl exec -n ingress-nginx deploy/ingress-nginx-controller -- nginx -t.

  • Dump the full effective configuration with nginx -T when investigating routing or TLS issues.

  • Verify backend endpoints with kubectl get endpoints <service>; a Service with no ready endpoints commonly causes 503 responses.

Best Practices and Common Pitfalls

  • Prefer pathType: Prefix or Exact unless regex behavior is specifically required.

  • Remember that proxy_pass behavior changes with trailing slashes; test rewrites carefully.

  • Use readiness and liveness probes on controller Pods and backend Pods.

  • Do not assume an Ingress change is instant; watch for controller errors and reload failures.

  • Keep TLS certificates rotated and monitor expiration independently of Ingress status.

69

How do you monitor Nginx using stub_status?

stub_status is Nginx’s built-in status module for lightweight connection and request monitoring. It exposes instance-wide counters, so use it for capacity trends and connection-state signals rather than detailed HTTP telemetry or end-to-end health checks.

Read full answer

Applies toNginx 1.24+

How It Works

Nginx’s master process reads the configuration and manages workers; workers use non-blocking, event-driven I/O. The module exposes shared counters for the whole Nginx instance, not one virtual server.

Enable stub_status in a dedicated server on loopback or in a restricted location. Nginx first selects a server by listen address and server_name, then selects a location: exact = matches first, the longest prefix is remembered, and regular expressions are tested in order unless a ^~ prefix match skips them. The returned counters remain instance-wide regardless of which location was selected.

Metrics to Interpret

Use deltas between samples for rates rather than interpreting cumulative counters as current load.

Metric Meaning Operational interpretation
Active connections Current client connections, including idle keep-alive connections Compare with connection capacity, but do not treat it as concurrent requests
server accepts Cumulative TCP connections accepted Calculate the new-connection rate from deltas
server handled Cumulative TCP connections handled Normally equals accepts; sustained divergence warrants investigation
requests Cumulative HTTP requests processed HTTP/2 and HTTP/3 requests may share one connection
Reading Connections reading a client request header High values can indicate slow clients or traffic bursts
Writing Connections writing a response High values can indicate slow clients, backpressure, or expensive responses
Waiting Idle keep-alive connections awaiting another request Often healthy; high values alone do not prove overload

A full Nginx restart resets cumulative counters. Monitoring exporters should treat any observed decrease as a counter reset rather than calculating a negative rate.

Production Monitoring

A typical workflow is:

  1. Scrape the endpoint every 10–30 seconds from a local agent or exporter.

  2. Convert requests, accepts, and handled into per-second rates.

  3. Track active, reading, writing, and waiting connections as gauges.

  4. Alert on abnormal rates, connection saturation, scrape failures, or sustained accepts/handled divergence.

  5. Correlate results with access/error logs, upstream metrics, CPU, memory, file descriptors, and network saturation.

stub_status does not cover all Nginx observability needs:

Area Complementary production signal
Static files Use access logs for paths, status codes, and bytes served
Reverse proxy and load balancing Use upstream access/error logs and active health-check results
TLS Monitor TLS error logs and certificate-expiry checks
HTTP/2 and HTTP/3 Use stream-level or client-side telemetry when enabled
Caching and compression Log $upstream_cache_status; use $gzip_ratio when gzip is enabled
Rate limiting Use access logs and $limit_req_status to identify rejections or delays
Security headers Verify required response headers with synthetic HTTP checks

The endpoint is not an end-to-end health check, so a separate application or upstream check is still required.

Security and Failure Modes

Never expose stub_status directly to the public Internet. It has no built-in authentication or encryption. Prefer one of these designs:

  • Bind it to 127.0.0.1 and scrape it through a local agent.

  • Bind it to a private interface, restrict access with allow/deny, and enforce firewall rules.

  • Put it behind authenticated monitoring infrastructure.

The allow/deny mechanism provides IP-based access control, not identity-based authentication. Also, Active connections is not equivalent to active requests: one HTTP/2 connection can multiplex many streams, and one HTTP/3 QUIC connection can carry multiple streams.

Code Example

Common distribution and official builds include the status module. Their build flags normally show:

nginx -V 2>&1 | grep -F -- '--with-http_stub_status_module'

If the flag is absent, check the installed package or build options; nginx -t after adding the directive is definitive for the loaded configuration.

Create /etc/nginx/conf.d/stub_status.conf:

server {
    listen 127.0.0.1:8080;
    server_name 127.0.0.1 localhost;

    location = /stub_status {
        stub_status;
        access_log off;

        allow 127.0.0.1;
        deny all;
    }

    location / {
        return 404;
    }
}

Validate and reload Nginx, then verify the endpoint:

sudo nginx -t && sudo nginx -s reload
curl -fsS http://127.0.0.1:8080/stub_status

An illustrative response is:

Active connections: 3
server accepts handled requests
 100 100 250
Reading: 0 Writing: 1 Waiting: 2

Best Practices and Common Pitfalls

  • Do not expose the endpoint publicly: restrict it to loopback or a trusted monitoring network.

  • Do not alert only on active connections: keep-alive traffic can keep the value high without indicating saturation.

  • Do not infer application health from stub_status: it does not expose upstream failures, 5xx responses, latency, or certificate problems.

  • Handle counter discontinuities: treat decreases as resets and use rates derived from counter deltas.

  • Retain detailed logs: access and error logs provide the request, upstream, TLS, and failure context missing from stub_status.

  • Manage configuration as code: back it up, version it, run nginx -t, and validate changes during upgrades.

  • Establish baselines: compare connection and request rates before and after deployments to distinguish traffic changes from infrastructure regressions.

70

How do you perform zero-downtime deployments behind Nginx?

A zero-downtime deployment behind Nginx is achieved by starting healthy application instances, adding them to an upstream pool, gracefully reloading Nginx, and draining the old instances before stopping them. Nginx’s master process validates the new configuration and starts new workers, while old workers finish active requests instead of abruptly terminating connections.

Read full answer

Applies toNginx 1.24+ (open source; HTTP/3 requires a QUIC-enabled build)

How the Architecture Helps

Nginx uses a master process and one or more worker processes:

  • The master process reads the configuration, manages workers, and coordinates graceful reloads.

  • Workers use an event-driven architecture to handle many connections without one thread per connection.

  • During nginx -s reload, new workers use the updated configuration and accept new connections.

  • Old workers stop accepting new connections, complete existing requests, and then exit.

This makes configuration reloads non-disruptive, but it does not make the application deployment safe by itself. The application instances must support health checks, graceful shutdown, and request draining.

Recommended Deployment Flow

  1. Deploy the new application version to a new port or host.

  2. Verify the new instance directly with its health endpoint.

  3. Add the new instance to the Nginx upstream pool.

  4. Run nginx -t and reload Nginx gracefully.

  5. Monitor error rates, latency, and upstream connection failures.

  6. Remove the old instance from the pool and reload again.

  7. Wait for in-flight requests to drain, then stop the old instance gracefully.

For a blue-green deployment, deploy the new version into a separate upstream pool and switch proxy_pass from the old pool to the new one. This provides an explicit rollback point, although it temporarily requires capacity for both versions.

Nginx Configuration Example

Create /etc/nginx/upstreams/app_pool.conf:

server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;

Create /etc/nginx/conf.d/app.conf:

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

upstream app_pool {
    least_conn;
    keepalive 32;
    include /etc/nginx/upstreams/app_pool.conf;
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    client_max_body_size 10m;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    location / {
        limit_req zone=api_limit burst=20 nodelay;

        proxy_pass http://app_pool;
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        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_connect_timeout 2s;
        proxy_read_timeout 30s;

        proxy_next_upstream error timeout http_502 http_503 http_504;
    }
}

The certificate and key paths must exist before running nginx -t. The upstream include file lets deployment automation change the instance list without modifying the main server block.

Deployment Commands

Check a new instance before adding it to traffic:

curl --fail --silent --show-error --max-time 2 \
  http://10.0.0.13:8080/healthz

Add the new instance:

printf '%s\n' \
  'server 10.0.0.13:8080 max_fails=3 fail_timeout=30s;' \
  | sudo tee -a /etc/nginx/upstreams/app_pool.conf

sudo nginx -t && sudo nginx -s reload

The && is important: Nginx is not reloaded if the configuration test fails. After monitoring the new instance, remove the old server from the upstream include file, repeat nginx -t, and reload again. Stop the old application only after its in-flight request count reaches zero; use a graceful termination signal rather than kill -9.

Production Trade-offs and Pitfalls

  • Passive versus active health checks: Open-source Nginx uses passive failure detection through max_fails and fail_timeout; it does not continuously probe application health endpoints. Nginx Plus provides active health_check support.

  • Proxy URI behavior: proxy_pass http://app_pool; preserves the original request URI. proxy_pass http://app_pool/; in a matching location can replace the matched location prefix. For example, /api/users may become /users; choose the form carefully.

  • Keepalive behavior: keepalive requires HTTP/1.1 upstream connections and usually proxy_set_header Connection "";. Otherwise upstream connections may not be reused as intended.

  • Retries: proxy_next_upstream can mask a failing instance, but retries should not be enabled for non-idempotent operations unless duplicate processing is explicitly acceptable.

  • Security: Keep application ports private with firewall or cloud security-group rules. Terminate TLS at Nginx, validate forwarded headers only from trusted proxies, and rate-limit abusive clients.

  • Monitoring: Track 502, 503, and 504 responses, upstream response time, connection failures, and active requests. Keep the old configuration available for rollback and reload it only after validating it.

  • Data changes: Zero-downtime HTTP deployment does not make database migrations safe. Use backward-compatible, expand-and-contract schema changes, test migration timing, and maintain tested backups before risky releases.

  • Protocols: The example enables HTTP/2 over TLS with listen 443 ssl http2. HTTP/3 requires Nginx builds and environments with QUIC support, and should be enabled separately after validating client and network compatibility.

71

How do you configure Nginx for large file uploads and downloads?

Nginx handles large transfers by separating buffering for clients, upstreams, and temporary files, then tuning body limits, inactivity timeouts, and storage. For very large production objects, direct uploads to object storage and CDN-backed downloads usually reduce origin load and failure domains.

Read full answer

Applies toNginx OSS 1.24+

How It Works

  • The master process parses the configuration and manages event-driven worker processes, which handle connections and transfers.

  • server blocks select virtual hosts. Within a server, location matching chooses the handler: exact (=) matches take priority, then the longest prefix; regular expressions are checked afterward unless the prefix uses ^~.

  • client_max_body_size limits request bodies and defaults to 1m. A larger body produces 413 Payload Too Large.

  • Bodies larger than client_body_buffer_size can be written to temporary files. Large concurrency can therefore consume substantial disk or memory.

  • proxy_request_buffering controls incoming request-body buffering, while proxy_buffering controls upstream response buffering.

  • HTTP/2 is supported by Nginx OSS 1.24+. HTTP/3 requires a build or product that includes it; stock Nginx OSS 1.24 does not provide HTTP/3. Neither protocol removes body, timeout, or disk constraints.

  • An upstream group can load-balance requests across application servers using round-robin selection by default.

Upload and Download Tuning

Directive Precise behaviour
proxy_request_buffering on Buffers the complete body before forwarding it, isolating the upstream from client speed. Retries still depend on proxy_next_upstream, idempotency, and whether the body was already sent.
proxy_request_buffering off Sends the body as it arrives, reducing local disk use. Once sent, the body generally cannot be replayed if the upstream fails.
proxy_buffering off Disables Nginx response buffering and passes upstream data through as it arrives, coupling the upstream transfer to the client’s consumption rate.
proxy_max_temp_file_size Limits the maximum temporary file used for a buffered upstream response. 0 disables temporary-file buffering; it does not disable in-memory proxy buffers.
  • client_body_timeout, proxy_send_timeout, proxy_read_timeout, and send_timeout are inactivity timeouts between successive operations, not total-transfer limits.

  • sendfile on efficiently serves static files and does not apply to proxied application responses. Nginx static files support byte-range requests for resumable downloads.

  • X-Accel-Redirect lets an authorized application hand file delivery to Nginx. The target must use an internal location so clients cannot request it directly.

  • Avoid client_max_body_size 0 unless unbounded uploads are an explicit, safely controlled requirement.

Code Example

This configuration demonstrates buffered and streamed uploads, static and streamed downloads, and application-authorized delivery:

worker_processes auto;

events {
    worker_connections 4096;
}

http {
    sendfile on;

    upstream app_backend {
        server 10.0.0.10:8080;
        server 10.0.0.11:8080;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;

        send_timeout 300s;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_send_timeout 300s;
        proxy_read_timeout 300s;

        add_header X-Content-Type-Options nosniff always;

        # Buffer the complete upload before contacting the application.
        location /upload/ {
            client_max_body_size 10g;
            client_body_timeout 300s;
            client_body_buffer_size 1m;
            proxy_request_buffering on;
            proxy_pass http://app_backend;
        }

        # Stream the upload directly to the application.
        location /upload-stream/ {
            client_max_body_size 10g;
            client_body_timeout 300s;
            proxy_request_buffering off;
            proxy_pass http://app_backend;
        }

        location /downloads/ {
            root /srv/downloads;
        }

        # Stream an upstream-generated download without response buffering.
        location /download-stream/ {
            proxy_buffering off;
            proxy_pass http://app_backend;
        }

        # Only an internal redirect from the application may access this path.
        location /protected/ {
            internal;
            alias /srv/protected/;
        }
    }
}

The authorized application can return:

X-Accel-Redirect: /protected/report.zip
Content-Type: application/zip
Content-Disposition: attachment; filename="report.zip"

Validate and reload the configuration:

sudo nginx -t && sudo nginx -s reload

With proxy_pass http://app_backend;, /upload/a.zip remains /upload/a.zip upstream. With proxy_pass http://app_backend/;, the matched /upload/ prefix is replaced, producing /a.zip.

Production Operations

  • Monitor temporary-disk usage, memory, network throughput, upstream saturation, and $request_length, $bytes_sent, $request_time, and $upstream_response_time.

  • Use TLS at the edge and authenticate uploads. Apply limit_conn and limit_req with an appropriate key; neither is a byte quota.

  • Cache public downloads at a CDN or with proxy_cache. Avoid gzipping archives, video, and other already-compressed payloads because it consumes CPU without materially reducing transfer size.

  • Prefer presigned direct-to-object-storage uploads and CDN downloads for very large objects. Keep source objects backed up and versioned; Nginx temporary files are not durable storage.

  • Upgrade by validating configuration on a canary host and reloading gracefully. Set worker_shutdown_timeout deliberately because expiration can terminate existing transfers.

Common Pitfalls

  • Raising client_max_body_size without sizing temporary storage can turn Nginx into a disk bottleneck.

  • proxy_buffering affects upstream responses; use proxy_request_buffering for streaming uploads.

  • A public X-Accel-Redirect target defeats the authorization model; keep the location internal and validate generated paths.

  • Long transfers still encounter inactivity timeouts even when the total transfer duration is unlimited.

72

How does Nginx use the X-Accel-Redirect response header?

X-Accel-Redirect is an Nginx response-header mechanism that lets a trusted upstream application ask Nginx to serve the response from an internal location instead of returning the application’s response body directly to the client. Nginx consumes the header, performs an internal redirect, and uses the target location’s content handlers, such as static-file serving or another reverse proxy.

Read full answer

Applies toNginx 1.24+

How It Works

  1. The client sends a request to Nginx.

  2. Nginx forwards the request to an upstream application.

  3. The application returns a response containing a header such as:

http X-Accel-Redirect: /protected/report.pdf

  1. Nginx treats /protected/report.pdf as an internal URI and rematches it against its location configuration.

  2. The response is produced by that internal location, while the client normally does not receive the X-Accel-Redirect header itself.

The internal location can serve a file directly:

location /protected/ {
    internal;
    alias /var/www/protected/;
}

It can also use proxy_pass, return a generated response, or use other content handlers. The upstream application does not need to send the protected file’s contents through the public request path.

This differs from the X-Sendfile header used by Apache and other servers; Nginx does not natively support X-Sendfile (though third-party modules exist), and instead uses X-Accel-Redirect for internal redirects.

Nginx Architecture and Matching

Nginx uses a master process and worker processes. The master reads and validates the configuration, while workers handle connections using an event-driven architecture. An internal redirect remains within the same worker and does not create a new external HTTP request.

Configuration is hierarchical, typically following:

main context
└── http context
    └── server block
        └── location block

For location selection, Nginx generally checks exact matches first, then the longest matching prefix, and then regular expressions according to the applicable prefix and regex rules. The internal directive prevents direct client access to the location; a direct request normally receives 404 Not Found.

The header should contain a trusted internal URI. Absolute URLs or user-controlled values can create unsafe redirect behavior if the upstream is compromised or incorrectly implemented.

Code Example

The following configuration is valid in an Nginx http context:

upstream app {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://app;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /protected/ {
        internal;
        alias /var/www/protected/;
    }
}

The application handling /download should return:

HTTP/1.1 200 OK
X-Accel-Redirect: /protected/report.pdf
Content-Type: application/octet-stream

With the alias shown above, Nginx maps the internal URI /protected/report.pdf to /var/www/protected/report.pdf.

The proxy_pass form matters. In location /, proxy_pass http://app; preserves the original request URI when forwarding it. If a URI is included in proxy_pass, such as proxy_pass http://app/;, Nginx replaces the matched location prefix with that URI. This distinction is important in locations such as /api/.

Production and Operational Behavior

  • TLS: TLS commonly terminates at Nginx. The upstream connection should still be protected with HTTPS or a trusted private network when appropriate.

  • HTTP/2 and HTTP/3: The mechanism is based on HTTP response headers and is independent of the client-facing protocol. HTTP/2 and HTTP/3 require the corresponding Nginx build and configuration support.

  • Caching: The internal target can use Nginx caching or static-file optimizations, but cache invalidation and storage permissions must be designed for the protected content.

  • Compression: gzip and related directives apply according to the location and response headers; they do not alter the internal-redirect mechanism.

  • Rate limiting: Apply limit_req and similar protections to the public entry location, while ensuring the internal target does not unintentionally bypass required controls.

  • Security headers: Add headers such as Strict-Transport-Security, X-Content-Type-Options, and Content-Security-Policy where appropriate. The exact policy depends on the delivered content.

  • Monitoring: Monitor upstream errors, internal-location 404 responses, file permission failures, and latency. A log format containing both $request_uri and $uri helps distinguish the original client request from the current internal URI.

Common Pitfalls

  • Omitting internal: The protected location may become directly accessible.

  • Trusting arbitrary upstream headers: Only a controlled upstream should be allowed to generate X-Accel-Redirect; do not reflect a client-provided value into it.

  • Incorrect alias mapping: Remember that the trailing slash affects how the location prefix is replaced.

  • Assuming the upstream body is visible: Nginx normally replaces the public response with the internal location’s response.

  • Confusing it with a client redirect: It is an internal Nginx redirect, not a 302 response telling the browser to request another URL.

  • Ignoring authorization boundaries: Perform authentication and authorization before the upstream emits the header, and ensure the internal target cannot expose files outside the intended directory.

73

How should Nginx be configured behind Cloudflare?

Use a proxied Cloudflare DNS record, terminate public TLS at Cloudflare, and configure Nginx for a separate TLS connection from Cloudflare using Full (strict) mode. Restore the original client IP from trusted Cloudflare addresses and prevent direct access to the origin.

Read full answer

Applies toNginx 1.24+ with Cloudflare's current continuously deployed edge services

How It Works

  • Cloudflare edge: Terminates client connections and provides DNS routing, caching, WAF rules, rate limiting, and client-facing HTTP/2 or HTTP/3.

  • Origin protocol: Cloudflare’s client-facing protocol does not determine the edge-to-origin protocol. The example therefore uses HTTP/1.1 over TLS to the origin, which is valid across Nginx 1.24+.

  • Nginx architecture: A master process reads the configuration and launches workers that use event-driven, nonblocking I/O.

  • Routing: Nginx selects a server block using Host and TLS SNI. Exact = locations take priority, the longest prefix is remembered, and regex locations are tested in configuration order unless the prefix uses ^~.

  • Client IP restoration: CF-Connecting-IP supplies the original address, but it is trusted only when the connection comes from a known Cloudflare address.

  • Static files and load balancing: Suitable /assets/ requests can be served locally and cached at the edge. An Nginx upstream pool provides round-robin load balancing; max_fails and fail_timeout provide passive failure handling rather than active health checks.

Cloudflare and Origin Setup

  1. Create an A or AAAA record for app.example.com and enable the orange-cloud proxy.

  2. Install an Origin CA certificate and private key at the paths used below, or use another certificate trusted by Cloudflare.

  3. Select Full (strict). Avoid Flexible, which does not encrypt the Cloudflare-to-origin connection.

  4. Restrict origin ports 80 and 443 to Cloudflare’s published IP ranges. Permit administration through a VPN or separate allowlist.

  5. Generate Nginx’s trusted Cloudflare IP list from Cloudflare’s official IPv4 and IPv6 endpoints.

Code Example

Generate the trusted Cloudflare address file:

set -euo pipefail

tmp=$(mktemp)
{
  printf '# Generated from Cloudflare IP ranges\n'
  curl -fsSL https://www.cloudflare.com/ips-v4 | sed 's/^/set_real_ip_from /'
  curl -fsSL https://www.cloudflare.com/ips-v6 | sed 's/^/set_real_ip_from /'
} > "$tmp"

sudo install -m 0644 "$tmp" /etc/nginx/cloudflare-real-ip.conf
rm -f "$tmp"

Create /etc/nginx/conf.d/app.example.com.conf:

upstream app_upstream {
    server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

log_format cloudflare
    '$remote_addr $status $request_time '
    'cf_ray="$http_cf_ray" '
    'cf_cache="$http_cf_cache_status" '
    'upstream_addr="$upstream_addr" '
    'upstream_response_time="$upstream_response_time" '
    '"$http_user_agent"';

server {
    listen 80;
    server_name app.example.com;

    return 308 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name app.example.com;

    ssl_certificate     /etc/nginx/tls/app.example.com.pem;
    ssl_certificate_key /etc/nginx/tls/app.example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    server_tokens off;

    include /etc/nginx/cloudflare-real-ip.conf;
    real_ip_header CF-Connecting-IP;

    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    access_log /var/log/nginx/access.log cloudflare;

    location /assets/ {
        root /var/www;
        expires 1h;
        try_files $uri =404;
    }

    location / {
        proxy_pass http://app_upstream;
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header CF-Connecting-IP $remote_addr;

        proxy_connect_timeout 5s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

Validate and reload safely:

sudo nginx -t
sudo nginx -s reload

proxy_pass http://app_upstream; has no URI component, so Nginx preserves the original request path. proxy_pass http://app_upstream/; uses / as the replacement URI and replaces the matched location prefix.

Production Practices

  • Caching: Cache static assets at Cloudflare and bypass APIs, authenticated responses, and personalized HTML. Avoid overlapping Nginx proxy_cache and Cloudflare caching unless keys, cookies, and purging are coordinated.

  • Compression: Choose the Cloudflare or Nginx compression layer deliberately. If Cloudflare compression is enabled, avoid compressing the same responses again at Nginx unless required by the upstream contract.

  • Rate limiting: Prefer Cloudflare rules for distributed enforcement. Nginx can define limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s; in the http context and apply limit_req to protected locations.

  • Security: Manage CSP and HSTS deliberately because they affect dependent domains. Cloudflare Origin CA certificates are trusted by Cloudflare, not directly by browsers.

  • Monitoring: The example logs the restored IP, Ray ID, cache status, upstream address, and upstream response time. Alert on Nginx 5xx, Cloudflare 52x, origin latency, certificate expiry, and traffic shifts.

  • Maintenance: Back up certificates, keys, and configuration; version-control templates without private keys; automate IP-list updates and certificate renewal; and validate configuration before staged upgrades.

Common Failure Modes

  • Cloudflare 525: TLS handshake failed. Check certificate validity, key matching, protocols, and the origin firewall.

  • Cloudflare 526: The origin certificate failed strict validation. Install a valid Origin CA or publicly trusted certificate.

  • Cloudflare 502: Check Nginx logs, upstream health, timeouts, and proxy_pass paths.

  • Spoofed client IP: If the origin is publicly reachable, attackers can forge Cloudflare headers. The firewall must allow only Cloudflare ranges.

  • Stale caching or incorrect limits: Verify CF-Cache-Status, CF-Ray, restored $remote_addr, and the current Cloudflare IP ranges.

74

Which common Nginx misconfigurations create security vulnerabilities?

Common NGINX security failures usually involve broken trust boundaries, unsafe request handling, excessive exposure, or missing resource controls. A NGINX misconfiguration can expose files, enable SSRF, bypass authorization, weaken TLS, or allow traffic to overwhelm upstream services.

Read full answer

Applies toNGINX OSS 1.24–1.28

Common Security Failures

Misconfiguration Security impact Safer approach
Incorrect alias or root mappings May expose files outside the intended directory Prefer root; tightly bound any alias and avoid combining it with try_files
User-controlled proxy destinations or forwarded Host Enables SSRF or routes requests to the wrong virtual host Use fixed upstreams and validated hostnames
Trusting incoming X-Forwarded-* headers Attackers can spoof IP addresses or authenticated identities Overwrite them at the edge and trust only known proxies
Redirecting to $host Creates an open redirect when the request’s host is attacker-controlled Redirect to a fixed canonical hostname
Overbroad proxying or locations Exposes admin, internal, or unauthenticated endpoints Route only required paths and enforce authorization at the owning service
Missing body, connection, or request limits Enables large uploads, slow connections, and request floods Set client_max_body_size, timeouts, limit_conn, and limit_req
Weak TLS configuration Permits obsolete protocols or weak negotiation Allow only TLS 1.2 and TLS 1.3 and automate certificate renewal
Exposed dotfiles, logs, or backups Reveals credentials, source code, or infrastructure details Deny sensitive paths and keep secrets outside the document root
Treating server_tokens off as a control Hides the version without mitigating the vulnerability Patch, isolate, authorize, and monitor instead

URI, Location, and Header Pitfalls

The trailing slash in proxy_pass changes the forwarded path:

Configuration Request Path received upstream
location /api/ { proxy_pass http://app; } /api/users /api/users
location /api/ { proxy_pass http://app/; } /api/users /users

This can bypass upstream path-based authorization. Location selection checks exact matches first, then the longest prefix; a ^~ prefix stops regex matching, otherwise regex locations are tested in order, and the longest prefix is the fallback.

Other common errors include:

  • Using complex if blocks for rewrites or proxying; if runs during the rewrite phase and has surprising inherited behavior.

  • Forwarding $http_host, which contains the untrusted client-supplied host. Forward a validated host or $host when the server-name policy guarantees it.

  • Using proxy_add_x_forwarded_for without first removing untrusted values. At the public edge, overwrite the header with $remote_addr; append only behind a trusted proxy chain.

  • Trusting X-Real-IP or X-Forwarded-For without restricting set_real_ip_from to known proxy CIDRs.

  • Assuming limit_req is global. Its key is normally the client address, so inaccurate client-address derivation can undermine enforcement.

  • Relying on an internal location for authorization. External requests cannot directly select it, but the resource-owning service must still authorize access.

Architecture and Service Boundaries

NGINX normally uses a master process and event-driven worker processes. The master performs privileged operations and manages workers; workers handle connections and should run with reduced privileges. Efficient event handling does not replace application-level authorization, request-cost controls, or upstream timeouts.

  • Reverse proxy and load balancing: NGINX forwards requests but does not validate authorization or upstream identity automatically. Do not let an unvalidated Host select tenants or backends, and secure the NGINX-to-upstream network boundary with network policy or mTLS where required.

  • Caching: Personalized or sensitive responses can leak between users if cached without an appropriate key, bypass rule, and Cache-Control policy. Never rely on caching alone for authorization.

  • Compression: Compression can enable BREACH-style attacks when an attacker can induce requests containing reflected secrets and observe compressed response sizes. Avoid compressing secret-bearing responses.

  • HTTP/2: On NGINX 1.25.1 and later, use http2 on;. NGINX 1.24 requires the older listen 443 ssl http2; compatibility syntax.

  • HTTP/3: HTTP/3 requires QUIC, UDP 443, a compatible build, and suitable firewall or load-balancer support. From NGINX 1.25.0 onward, configure listen 443 quic; with http3 on;; NGINX OSS 1.24 has no built-in HTTP/3 support.

  • TLS termination: Configure ssl_protocols TLSv1.2 TLSv1.3;, redirect HTTP to HTTPS, and secure the separate connection from NGINX to the upstream.

Validation and Troubleshooting

Validate the complete configuration with sudo nginx -t before running sudo nginx -s reload; on systemd distributions, sudo systemctl reload nginx performs the reload. A failed test prevents the chained reload, but successful syntax validation does not prove correct routing or authorization.

Test routing, forwarded headers, limits, TLS, caching, and error responses externally after every change. Monitor upstream timeouts, client-closed requests (499), 502, 503, and 504 responses, active connections, TLS expiry, and unusual request rates. Keep logs protected, avoid recording query strings, cookies, or authorization headers, and monitor disk usage.

Production Hardening

Restrict real_ip trust to known proxy CIDRs, patch NGINX and upstream applications, and keep configuration under version control. Add Strict-Transport-Security, X-Content-Type-Options, Referrer-Policy, and an application-specific Content Security Policy with always; add HSTS only after confirming every covered subdomain supports HTTPS. Back up configuration, certificates, and keys, restrict key permissions, test restoration, and validate planned upgrades before deployment.

75

How do I proxy /api and serve static files in Nginx?

Use a prefix location to proxy /api/ to an upstream service and a separate location / to serve files from the document root. A trailing slash on proxy_pass determines whether Nginx forwards /api/ as part of the backend URI.

Read full answer

Applies toNginx Open Source 1.24+ on Linux

Routing and Matching

Nginx selects a location in this order:

  1. An exact match such as location = /api.

  2. The longest matching prefix location.

  3. If that prefix uses ^~, regular-expression locations are skipped; otherwise, regular expressions are tested in configuration order.

In the example below, location ^~ /api/ is the longest prefix for API paths, so it prevents later regular-expression locations from handling them.

The URI passed to the upstream depends on proxy_pass:

Configuration Backend request URI
proxy_pass http://api_backend/; /api/users becomes /users
proxy_pass http://api_backend; /api/users remains /api/users

Use the trailing-slash form when the backend expects paths relative to its root. Use the no-slash form when it expects the complete /api/... path.

Architecture and Upstream Behavior

Nginx uses a master process to read the configuration, manage workers, and coordinate reloads. Worker processes handle connections with an event-driven, non-blocking I/O model rather than dedicating a thread to every request.

worker_processes controls the number of workers, while worker_connections limits each worker’s total simultaneous connections, including upstream connections. The upstream block uses round-robin selection by default and supports passive failure handling through max_fails and fail_timeout; Nginx Open Source does not provide active health checks.

Code Example

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server_tokens off;

    access_log /var/log/nginx/access.log combined;
    error_log  /var/log/nginx/error.log warn;

    upstream api_backend {
        server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
        server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    server {
        listen 80;
        server_name example.com;

        root  /var/www/example;
        index index.html;

        # Required for upstream keepalive connections.
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        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_connect_timeout 5s;
        proxy_read_timeout    60s;

        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;

        # Canonicalize /api to /api/.
        location = /api {
            return 308 /api/;
        }

        # Replace /api/ with / when forwarding to the backend.
        location ^~ /api/ {
            proxy_pass http://api_backend/;
        }

        # Deny hidden files while allowing /.well-known/.
        location ~ /\.(?!well-known) {
            deny all;
        }

        # Serve files and directories from the document root.
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

Validate and reload the configuration with:

sudo nginx -t
sudo nginx -s reload

A graceful reload starts new workers while old workers stop accepting new connections and finish their existing requests.

Production Operations, Security, and Pitfalls

  • TLS and protocols: Configure certificate and key paths and normally allow only TLS 1.2 and TLS 1.3. Nginx 1.24 through 1.25.0 enables HTTP/2 with listen 443 ssl http2;; Nginx 1.25.1+ also provides the http2 on; directive. HTTP/3 requires a QUIC-enabled Nginx 1.25.0+ build, listen 443 quic reuseport;, http3 on;, and open UDP port 443.

  • Monitoring: Record $upstream_status, $request_time, and $upstream_response_time in a custom log format. Alert on upstream failures, elevated 5xx rates, timeouts, worker saturation, and file-descriptor exhaustion.

  • Rate limiting: Define limit_req_zone $binary_remote_addr zone=api_limit:10m rate=20r/s; in http, then apply limit_req zone=api_limit burst=40 nodelay; inside the API location.

  • Caching and compression: Cache only responses with suitable cacheability and validation headers. Use the core gzip module for general compression; Brotli requires a separately supplied module such as ngx_http_brotli_module. Do not repeatedly compress already compressed assets.

  • Failure behavior: Connection failures generally produce 502 Bad Gateway, while upstream timeouts can produce 504 Gateway Timeout. The static =404 fallback prevents unknown paths from being proxied accidentally.

  • Deployment safety: Back up configuration and document roots, deploy static assets atomically, preserve permissions for the Nginx worker, and run nginx -t before every reload.

  • Proxy trust: If another load balancer is in front, configure real_ip_header and trusted proxy ranges carefully. Otherwise, client addresses and forwarded headers may be spoofed or recorded incorrectly.

76

How does Nginx load balance three application servers behind HTTPS?

Nginx can terminate TLS at the edge and use least-connections load balancing across three application servers. Application requests use HTTPS; port 80 remains available for ACME challenges and redirects to HTTPS.

Read full answer

Applies toNginx 1.24+ on Ubuntu 24.04

Architecture, Matching, and Upstream Selection

  • The master process reads the configuration and manages workers. Workers use an event-driven connection loop rather than creating a thread per request.

  • least_conn selects the upstream server with the fewest active connections. max_fails and fail_timeout provide passive failure handling; open-source Nginx does not actively probe application health, while active checks require Nginx Plus.

  • Location matching checks exact = matches first, then remembers the longest prefix. Regex locations are tried in configuration order unless the winning prefix uses ^~; if no regex matches, the prefix is used.

  • root serves static files by mapping the request URI beneath a filesystem directory. The ACME location below therefore exposes only Certbot’s challenge files.

TLS and Proxy Routing

  • Nginx decrypts client TLS in its workers. proxy_pass http://application_servers; preserves the request URI, while proxy_pass http://application_servers/; replaces the matched location prefix with /.

  • This example uses literal upstream IPs. If upstream hostnames are used, Nginx resolves them when the configuration loads; reload after DNS changes or use a resolver with variable-based proxying for runtime re-resolution.

  • For HTTPS upstreams, use server 10.0.0.11:443 ssl; and proxy_pass https://application_servers;, together with proxy_ssl_server_name on;, proxy_ssl_name app.internal.example.com;, proxy_ssl_verify on;, proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;, and an appropriate proxy_ssl_verify_depth.

Code Example

Ubuntu’s /etc/nginx/nginx.conf owns the top-level events and http blocks. Save this as a site fragment; it is included from the http context:

sudo apt update
sudo apt install -y nginx certbot
sudo systemctl enable --now nginx certbot.timer
sudo mkdir -p /var/www/html
sudo certbot certonly --webroot -w /var/www/html -d example.com
server_tokens off;

log_format upstream_timing '$remote_addr - $remote_user [$time_local] '
                          '"$request" $status $body_bytes_sent '
                          'rt=$request_time upstream=$upstream_addr '
                          'ustatus=$upstream_status urt=$upstream_response_time';

access_log /var/log/nginx/access.log upstream_timing;

upstream application_servers {
    zone application_servers 64k;
    least_conn;

    server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
    server 10.0.0.13:8080 max_fails=3 fail_timeout=30s;

    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    location ^~ /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        return 301 https://example.com$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    client_max_body_size 10m;

    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    location / {
        proxy_pass http://application_servers;
        proxy_http_version 1.1;

        # Clear Connection for upstream keepalive.
        proxy_set_header Connection "";

        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 https;

        proxy_connect_timeout 5s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        # Non-idempotent requests are not retried after transmission
        # unless the non_idempotent option is explicitly enabled.
        proxy_next_upstream error timeout http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        proxy_next_upstream_timeout 10s;
    }
}

Install and validate the fragment:

sudo install -m 0644 app-lb.nginx /etc/nginx/sites-available/app-lb
sudo ln -sfn /etc/nginx/sites-available/app-lb /etc/nginx/sites-enabled/app-lb
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx

Production Operations and Troubleshooting

  • Monitor HTTP 5xx rates, upstream timeouts, $upstream_status, $upstream_response_time, active connections, and traffic distribution across the three peers.

  • After max_fails failures during fail_timeout, a peer is considered unavailable. Do not enable non_idempotent unless duplicate POST or PATCH processing is safe.

  • Verify certbot.timer and renewal events. Back up the private key and configuration securely; if the key is lost, revoke or replace the certificate as appropriate.

  • Test upgrades with nginx -t, retain rollback configuration, and reload rather than restart so existing requests can finish.

  • Use nginx -T to inspect the complete expanded configuration, inspect /var/log/nginx/error.log, and test routing with curl -v before and during an incident.

Security and Performance

  • Restrict 10.0.0.11-13:8080 to the Nginx host with host or cloud firewalls. Treat Nginx as the application’s trust boundary and do not blindly trust client-supplied forwarding headers.

  • Enable HSTS only after confirming that the affected domain and any included subdomains support HTTPS. Keep the certificate key out of source control.

  • Use gzip selectively. Define proxy_cache_path and use proxy_cache with proxy_cache_valid for cacheable responses, excluding personalized or sensitive data.

  • Define limit_req_zone in the http context and apply limit_req to suitable locations, accounting for legitimate bursts and trusted proxy addresses.

  • Nginx 1.24 supports listen 443 ssl http2;. Nginx 1.25.1 and later use listen 443 ssl; with http2 on;. proxy_http_version 1.1 controls only the upstream hop.

  • HTTP/3 requires Nginx 1.25.0 or later with QUIC support, UDP port 443, and compatible firewalls, load balancers, and client networks.

77

How to debug Nginx returning 404 for all pages?

When Nginx suddenly returns 404 for every request, the cause is almost always a routing mismatch rather than missing content: the wrong server block is selected, a location no longer matches, root/alias points at the wrong directory, or a recent reload activated a broken config. The fastest path is to validate the config, read the error log, and confirm which server block and file path Nginx actually resolves.

Read full answer

Applies toNginx 1.24+ (open source) on Linux.

Step-by-Step Debugging

  1. Confirm the symptom and scope. Reproduce with curl -v http://example.com/ and check whether the 404 is returned for static assets too. Note the Server header and any X-... headers to confirm you are hitting the expected instance.

  2. Validate configuration. Run sudo nginx -t. A failed test means the last reload may have failed or an include is broken; check sudo nginx -T to dump the merged config and search for the active server blocks.

  3. Check service state and recent changes. systemctl status nginx and journalctl -u nginx --since "1 hour ago". Look for failed reloads, permission errors, or a new deployment that changed /etc/nginx.

  4. Read the error log. tail -f /var/log/nginx/error.log while reproducing. A line like open() "/var/www/html/index.html" failed (2: No such file or directory) reveals the exact resolved path.

  5. Inspect the access log. tail -f /var/log/nginx/access.log confirms the request URI and response status (the default combined format does not record the Host header; add $host with a custom log_format); if proxied, include $upstream_status in the log format to identify an upstream 404.

  6. Verify server block selection. Nginx picks the server block by listen + server_name (exact, then longest wildcard, then regex, then default_server). A missing or wrong server_name causes requests to fall into the default block, which may have a different root. Test with curl -H "Host: example.com".

  7. Verify file existence and permissions. ls -la /var/www/html/ and namei -l /var/www/html/index.html. The worker process user (www-data on Debian/Ubuntu, nginx on RHEL) needs read/execute on every path component.

  8. Check root vs alias and try_files. root appends the full URI; alias replaces the matched location prefix. A common mistake is root /var/www/html/app; inside location /app/, which resolves /app/x to /var/www/html/app/app/x.

Common Causes

Cause How to detect Fix
Wrong default server block nginx -T shows unexpected root Add default_server to the intended listen or fix server_name
root/alias mismatch Error log shows wrong path Correct directive; prefer root at server level
Missing files after deploy ls shows empty dir Restore files or fix deploy path
Permission denied (returns 403) Error log shows (13: Permission denied) chown -R www-data:www-data and chmod 755 dirs
try_files fallback to =404 Config has try_files $uri $uri/ =404; Adjust fallback or add index files
Trailing slash in proxy_pass Upstream returns 404 Remove or add slash deliberately per Nginx semantics
Case-sensitive filesystem File exists with different case Match case exactly

Code Example

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8080/;  # trailing slash strips /api/
        proxy_set_header Host $host;
    }

    access_log /var/log/nginx/example.access.log;
    error_log  /var/log/nginx/example.error.log warn;
}

Common Pitfalls

  • Reloading without testing: always run nginx -t before systemctl reload nginx; a bad config can leave the old process running or fail to apply.

  • Editing the wrong file: configs under /etc/nginx/sites-enabled/ are symlinks; editing a copy in sites-available without reloading does nothing.

  • Assuming 404 means missing file: with proxy_pass, the 404 may come from the upstream; check upstream logs and the access log upstream_status.

  • SELinux/AppArmor denials: on RHEL, ausearch -m avc may show denials even when Unix permissions look correct.

  • Caching: a CDN or proxy_cache may serve a stale 404; purge cache and test with Cache-Control: no-cache.

After fixing, re-run nginx -t, reload, and verify with curl -I plus a full page load; monitor error logs for a few minutes to catch recurring issues.

78

How do you migrate a website from Apache to Nginx?

A successful Apache-to-Nginx migration requires reproducing Apache’s externally observable behavior, validating both stacks in parallel, and switching traffic only after health checks and a rollback path are proven.

Read full answer

Applies toNginx 1.24+ and Apache HTTP Server 2.4.x on Debian/Ubuntu Linux

Migration sequence

  1. Inventory virtual hosts, aliases, redirects, rewrites, authentication, proxying, headers, compression, caching, TLS, modules, and .htaccess files:

bash sudo apache2ctl -S sudo apache2ctl -M sudo apache2ctl -t sudo find /var/www -name .htaccess -print

  1. Record expected statuses, headers, bodies, cookies, redirects, and timings for static, dynamic, authenticated, API, upload, WebSocket, and error requests, including trailing-slash variants.

  2. Install Nginx on a separate host with sudo apt-get install -y nginx. If both servers share a host, configure them to bind distinct addresses; the wildcard listen 80 configuration below cannot coexist with Apache on the same address.

  3. Translate the configuration, run nginx -t, compare equivalent requests, and test under production-like load. Lower DNS TTLs 24–48 hours beforehand, canary the change, and retain Apache unchanged throughout the rollback window.

Configuration mapping

Apache Nginx equivalent Migration note
VirtualHost server Put each hostname in the appropriate server block.
DocumentRoot root The effective location determines the filesystem path.
Alias alias alias replaces the matched location prefix.
ProxyPass proxy_pass The trailing URI changes the forwarded path.
ProxyPassReverse proxy_redirect Rewrites upstream Location and Refresh headers.
mod_rewrite rewrite, try_files, return Execution order and matching semantics differ.
.htaccess location and directives Nginx has no per-directory override mechanism.
mod_headers add_header Child locations can replace inherited header sets.
mod_deflate / mod_expires gzip / expires Review inherited and duplicate-compression behavior.

Nginx checks exact = locations first, then the longest prefix. ^~ prevents regex checking; otherwise regex locations are tested in configuration order.

For location /api/, proxy_pass http://app_backend; forwards the normalized /api/... URI, while proxy_pass http://app_backend/; replaces /api/ with /.

Nginx configuration example

This configuration serves static files and proxies application traffic. Replace the example addresses with the actual staging and backend addresses.

# /etc/nginx/conf.d/example.com.conf

upstream app_backend {
    server 127.0.0.1:8080;
    keepalive 16;
}

server {
    listen 80;
    server_name example.com www.example.com;

    root /srv/example.com;
    index index.html;

    location = /healthz {
        access_log off;
        default_type text/plain;
        return 200 "ok\n";
    }

    location /static/ {
        alias /srv/example.com/static/;
        expires 7d;
    }

    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        proxy_connect_timeout 5s;
        proxy_read_timeout 60s;
    }
}

Validate and reload it:

sudo mkdir -p /srv/example.com/static
sudo nginx -t
sudo systemctl reload nginx
curl --resolve example.com:80:10.0.0.20 http://example.com/

For a static-only site, use try_files $uri $uri/ =404;. Route PHP or CGI requests to PHP-FPM or another application server with fastcgi_pass.

Production behavior

  • Architecture: A master process supervises workers that share listening sockets and use an event-driven, non-blocking model rather than a process or thread per connection.

  • TLS and protocols: With public DNS, install certbot python3-certbot-nginx, then run sudo certbot --nginx -d example.com -d www.example.com --redirect. DNS-01 instead requires a provider-specific Certbot plugin and certbot certonly; then install the certificate in Nginx. Test renewal with sudo certbot renew --dry-run.

  • HTTP/2 and HTTP/3: Nginx 1.24 uses listen 443 ssl http2; Nginx 1.25.1+ supports http2 on. HTTP/3 requires Nginx 1.25.0+, a compatible QUIC/TLS build, and UDP port 443.

  • Capacity and caching: Multiple upstream servers use round-robin selection by default. Upstream keepalive requires HTTP/1.1 and an empty Connection header. Define proxy_cache_path before using proxy_cache; avoid caching personalized responses.

  • Compression and limits: Enable gzip for suitable text types without recompressing already compressed assets. Define limit_req_zone in the http context and apply limit_req to the intended location; it limits request rate, not server capacity.

Security, observability, and rollback

  • Set forwarded headers from a defined trust boundary. The example overwrites X-Forwarded-For; behind a CDN or load balancer, use Nginx real_ip with an explicit trusted-source allowlist instead.

  • Add Content-Security-Policy, X-Content-Type-Options, Referrer-Policy, and suitable Permissions-Policy headers. Enable HSTS only after HTTPS is stable across every affected hostname.

  • Monitor upstream latency, 4xx/5xx rates, saturation, TLS errors, and renewal failures. Use nginx -T for the effective configuration and correlate access_log and error_log with application logs.

  • Version-control configuration, securely back up Apache configuration and private keys, and canary Nginx upgrades. To roll back, run sudo systemctl stop nginx && sudo systemctl start apache2, then verify the public endpoint and error rates.

79

How to configure Nginx for traffic spikes?

Nginx absorbs traffic spikes by combining connection tuning, upstream keep-alive, response caching, graceful load shedding, and horizontal scaling behind a load balancer. The goal is to serve as much traffic as possible from cache and keep-alive connections, while shedding excess load with 503 (or 429 when configured) responses instead of exhausting workers.

Read full answer

Applies toNginx 1.24+ (open source) on Linux

How It Works

Nginx uses a master process plus worker processes. Each worker runs a single event loop, so a spike is handled by many concurrent connections per worker rather than one thread per connection. Tuning means raising the per-worker connection ceiling, the OS file-descriptor limit, and the listen backlog, then reducing work per request through caching and keep-alive.

Key Tuning Areas

  • Worker and connection limits: set worker_processes auto; and raise worker_connections (e.g. 4096-8192). Raise worker_rlimit_nofile and the OS nofile ulimit together, or Nginx logs “too many open files”.

  • Upstream keep-alive: reuse TCP connections to backends with an upstream keepalive pool plus proxy_http_version 1.1 and Connection "". This avoids connection churn during a spike.

  • Caching: proxy_cache with proxy_cache_lock on prevents a thundering herd on cache misses; proxy_cache_use_stale updating serves stale content while one request refreshes it.

  • Load shedding: limit_req and limit_conn return 503 by default (or 429 if configured with status=429) instead of queueing unbounded requests. Use burst with nodelay for short spikes.

  • Static assets: serve directly with sendfile, tcp_nopush, long expires, and immutable cache headers so Nginx never touches the app.

  • Compression and TLS: enable gzip (or brotli) and TLS session reuse (ssl_session_cache) to cut bandwidth and handshake cost.

Production Considerations

  • Monitor nginx_stub_status (active connections, waiting, reading, writing) and alert on waiting growth; that indicates saturation.

  • Set listen ... backlog=4096 and raise net.core.somaxconn to match; otherwise the kernel drops SYNs before Nginx sees them.

  • Use proxy_next_upstream carefully (only on error timeout) to avoid retry storms.

  • Cache invalidation: version asset filenames and use short TTLs for API responses; never cache authenticated or user-specific responses without Vary.

  • Rate-limit keys: $binary_remote_addr behind a CDN is the CDN’s IP; use $http_x_forwarded_for only after validating the trusted proxy.

Configuration Example

worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;

    limit_req_zone  $binary_remote_addr zone=api:10m rate=20r/s;
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=appcache:100m
                     max_size=2g inactive=60m use_temp_path=off;

    upstream backend {
        least_conn;
        server 10.0.0.10:8080 max_fails=3 fail_timeout=30s;
        server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
        keepalive 64;
    }

    server {
        listen 443 ssl http2 backlog=4096;
        server_name example.com;

        ssl_certificate     /etc/nginx/ssl/example.com.crt;
        ssl_certificate_key /etc/nginx/ssl/example.com.key;
        ssl_session_cache   shared:SSL:10m;
        ssl_session_timeout 10m;

        location /static/ {
            alias /var/www/static/;
            expires 30d;
            add_header Cache-Control "public, immutable";
        }

        location /api/ {
            limit_req zone=api burst=40 nodelay;
            limit_conn addr 30;

            # no trailing slash: preserve original request URI
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;

            proxy_cache appcache;
            proxy_cache_valid 200 30s;
            proxy_cache_use_stale error timeout updating http_500 http_502;
            proxy_cache_lock on;
            proxy_cache_lock_timeout 5s;
        }
    }
}

Best Practices

  • Validate with nginx -t before every reload; use nginx -s reload (graceful) rather than restart.

  • Size worker_connections against ulimit -n; a worker cannot exceed its fd ceiling.

  • Keep proxy_cache_lock on for hot keys to avoid origin stampedes.

  • Shed load early with limit_req at the edge; do not let queues grow unbounded.

  • Put Nginx behind a CDN for static and cacheable dynamic content; Nginx then handles only origin traffic.

  • Test with wrk/k6 against a staging instance and watch waiting connections and 5xx rates.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 79 Nginx answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All Cloud, DevOps & Infrastructure subjects