Nginx is a web server and reverse proxy for websites and APIs. This reference covers server and location, static files, proxy_pass, load balancing, caching and TLS.
nginx is an open-source HTTP server, reverse proxy and load balancer. It serves static files, terminates TLS and passes requests to an application; for non-HTTP traffic there is the stream module.
This reference describes the stable release line, nginx 1.30; mainline gets new features sooner (see the section “Versions and what’s new”).
In a typical setup nginx sits at the edge of the network: it accepts requests from the internet, serves static files itself and passes application requests over the internal network, for example to a Django process on 127.0.0.1:8000. A single nginx server often fills several roles at once.
nginx runs as several operating system processes: the master process reads the configuration and several worker processes handle connections. Workers use an event-based model and hold thousands of connections at the same time.
A typical setup: nginx serves static files itself, and application requests go over the internal network to port 8000.
Master and worker processes
The master process reads and validates the configuration and maintains the worker processes; it does not handle requests itself. The worker_processes directive sets the number of worker processes. It is the workers that accept and process requests.
To apply a new configuration without stopping, send the master process a reload signal. It checks the syntax of the new file; if it is valid, it starts workers with the new configuration and asks the old ones to finish their current requests and exit.
bashapply the configuration without stopping
nginx -s reload
nginx roles
Role
What nginx does
Web server
serves static files over HTTP and HTTPS
Reverse proxy
accepts client requests and passes them to an application: Django and Node.js over HTTP, PHP over FastCGI
Load balancer
distributes requests across several application servers
TLS termination
decrypts HTTPS and passes plain HTTP to the application over the internal network
A server block is a virtual server: nginx selects it by the host name and port of the request. Requests to /api/ go to the application on port 8000; for everything else nginx looks for files in the /var/www/example.com directory.
When nginx is a good fit, and when it is not
Choose nginx when you need to serve static files quickly, accept many simultaneous connections, terminate TLS and spread the load. It does not run application code: the configuration describes where to pass a request, and the application, a Django or Node.js process, handles it. nginx calls the PHP interpreter over FastCGI. It does not replace the database, sessions or the application’s cache either.
What you need to know first
HTTP: request, response, headers, status codes (see the HTTP and REST reference).
Basic Linux skills: files, permissions, processes, services (see the Linux reference).
TLS basics: how HTTPS differs from HTTP and why you need a certificate (see the section “HTTPS and TLS” in this reference).
Everyday nginx management commands and directives for common tasks: static files, proxying, TLS, limits, logs. First check the configuration with nginx -t, then reload it with nginx -s reload; the details are in the other sections of the reference.
On Linux, install nginx from the nginx.org repository, which provides fresh releases of both branches, stable and mainline. Installation comes down to adding the repository and running apt install or yum install for nginx; you verify it with nginx -v and by getting the placeholder page on port 80.
Ubuntu and Debian
First the prerequisite packages and the signing key, then the file with the repository address, and then the installation. You do all this once; after that nginx updates come from the same repository.
bashon the host, Ubuntu
sudo apt install curl gnupg2 ca-certificates lsb-release \ ubuntu-keyring# key for verifying the nginx package signaturescurl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \ | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
# stable; for mainline use the path packages/mainline/ubuntuecho "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \https://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" \ | sudo tee /etc/apt/sources.list.d/nginx.list# give nginx.org packages priority over the distribution’s packagessudo tee /etc/apt/preferences.d/99nginx <<EOFPackage: *Pin: origin nginx.orgPin: release o=nginxPin-Priority: 900EOF
The 99nginx file with priority 900 makes apt pick the package from nginx.org even when the distribution has its own nginx package. The stable repository is enabled by default; for mainline, change packages/ubuntu to packages/mainline/ubuntu in the address and leave everything else as it is. For the difference between the branches, see the section “Versions and what’s new”.
Debian is the same except in two places: the prerequisites include debian-archive-keyring, and the repository address uses packages/debian. Key verification, the priority file and the installation are identical.
The package creates the unprivileged nginx user and the log and cache directories, registers the nginx service and, on Ubuntu and Debian, starts it right away, so there is nothing more to start.
RHEL and derivatives
On RHEL and its derivatives (CentOS, Rocky Linux, AlmaLinux) the repository is described by the /etc/yum.repos.d/nginx.repo file: stable is enabled and mainline is added but disabled.
sudo yum install yum-utilssudo yum install nginx# start the service and enable it at boot in one gosudo systemctl enable --now nginx
When yum asks you to confirm the key, it shows the fingerprint; compare it with the one on the packages page and confirm. Enable the nginx-mainline repository with sudo yum-config-manager --enable nginx-mainline.
Verification
bashon the host
nginx -vsystemctl status nginxcurl -I http://localhost
textexample output
nginx version: nginx/1.30.6...● nginx.service - nginx - high performance web server Active: active (running) since ......HTTP/1.1 200 OKServer: nginx/1.30.6
nginx -v prints the version. In the systemctl status output, look at the Active line: on Ubuntu and Debian the installer has already started the service, so it should read active (running); on RHEL it is running after enable --now. curl -I requests only the headers; a 200 OK response and a Server header mean the placeholder page is answering on port 80. If something is wrong, look for the cause in /var/log/nginx/error.log; common errors are covered in the section “Common errors and troubleshooting”.
Where things are
Path
What it holds
/etc/nginx/nginx.conf
the main configuration file: a skeleton of contexts
/etc/nginx/conf.d/*.conf
files with server blocks, pulled in by the include directive
/etc/nginx/mime.types
mappings of file extensions to Content-Type headers
/etc/logrotate.d/nginx
log rotation: daily, 52 compressed copies
/usr/share/nginx/html
the placeholder page: index.html and 50x.html
/var/log/nginx/access.log
access log
/var/log/nginx/error.log
error log
/run/nginx.pid
process ID of the master process
nginx.conf already contains the line include /etc/nginx/conf.d/*.conf;, and conf.d/ holds default.conf, a server block that listens on port 80 and serves /usr/share/nginx/html. Describe your own site in a new file in conf.d/; after editing, check the configuration with nginx -t and apply it with sudo systemctl reload nginx. For how to write server blocks, see the section “Server blocks and server selection”; for how directives work, see “Configuration: contexts and directives”.
Distribution packages and building from source
nginx is also in the distributions’ own repositories, where an ordinary package manager installs it, but the distribution decides which versions it offers. On FreeBSD, install nginx as a package or build it with the ports system, which lets you choose build options. If you need a non-standard module, build nginx from source. In a container, the ready-made nginx image replaces installation: you mount the configuration and files as volumes. Running containers and volumes are covered in the Docker reference.
The nginx configuration is a text file made of directives: a simple directive ends with a semicolon, and a block directive holds other directives in curly braces. Container blocks are called contexts, and values from an outer context apply in nested ones until they are overridden.
The default file is called nginx.conf and lives in /etc/nginx, /usr/local/nginx/conf or /usr/local/etc/nginx, depending on how nginx was installed. Changes take effect after the configuration is reloaded, so check every edit with nginx -t and apply it with a reload.
How the file is organised
A directive consists of a name and parameters separated by spaces. Everything after a # to the end of the line is a comment. Instead of a semicolon, a block directive holds other directives in curly braces; if other directives can appear inside the braces, the block is called a context.
nginxnginx.conf: the skeleton of an installation
user nginx;worker_processes auto;error_log /var/log/nginx/error.log notice;pid /run/nginx.pid;events { worker_connections 1024;}http { include /etc/nginx/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; # site files, each with its own server blocks include /etc/nginx/conf.d/*.conf;}
Directives outside all blocks are in the main context; in the example above these are the process and log settings. The events and http blocks sit in main, server sits in http, and location sits in server. The events block configures connection handling; there can be any number of server and location blocks.
Context
Where it goes
What it configures
main
outside all blocks
processes, the error log, modules, include
events
in main
connection handling
http
in main
everything related to HTTP
server
in http
a virtual server: address, port, site names
location
in server or another location
requests with a matching URI
upstream
in http or stream
a group of servers for load balancing
stream
in main
TCP and UDP proxying
Inheritance
A child context inherits the directive values of its parent: a value from http applies in all its server blocks, and one from server in all its location blocks. A lower level takes precedence over a higher one if it repeats the directive itself.
nginxinheritance is overridden as a whole
server { add_header X-Frame-Options DENY; location /api/ { # X-Frame-Options no longer reaches this location add_header Cache-Control no-store; proxy_pass http://127.0.0.1:8000; }}
In such a location, list all the headers you need again, or turn on add_header_inherit merge: then the values from the outer level are added to the location’s own.
The main context describes the processes nginx starts before it serves any requests: which user the workers run as, how many there are, and where the error log goes.
Directive
Default
What it sets
user
nobody nobody
the user and group of the worker processes
worker_processes
1
the number of worker processes; auto uses the number of CPU cores
worker_connections
512
connections per worker process, in the events block
worker_rlimit_nofile
—
raises the open file limit so that it covers worker_connections
error_log
logs/error.log error
the error log file and level
pid
logs/nginx.pid
the file holding the master process ID
worker_connections counts all of a worker process’s connections, both to clients and to applications via proxy_pass, and it cannot exceed the open file limit, which worker_rlimit_nofile raises. The log levels are debug, info, notice, warn, error, crit, alert and emerg; a level also includes all the more severe messages.
Splitting the configuration into files
The include directive inserts a single file, or all files matching a mask, at the place where it appears; you can use it in any context. The main file holds the skeleton, and each site gets its own file in /etc/nginx/conf.d/.
nginxthe mask picks up every .conf file
include mime.types;include conf.d/*.conf;
The line include /etc/nginx/conf.d/*.conf; sits inside the http block, so the included files contain server blocks directly. The mask does not pick up a file that does not end in .conf.
Units and variables
Write numeric values with unit suffixes. For sizes these are k, K, m and M (kilobytes and megabytes), and offsets also accept g and G; time is measured in ms, s, m, h, d, w, M and y.
Notation
Meaning
1024, 8k, 1m
bytes, kilobytes, megabytes
1g
a gigabyte: the g suffix is allowed only for offsets
500ms, 30s
milliseconds, seconds
10m, 1h, 7d
minutes, hours, days
1M, 1y
a month is 30 days, a year is 365 days
1h 30m
a compound value: from larger units to smaller
A time without a suffix means seconds, but the documentation advises always writing a suffix, and some intervals support only whole seconds. The letter m means megabytes in a size and minutes in a time: in client_max_body_size 20m and proxy_read_timeout 10m they are different units.
Parameters can use variables, values that nginx computes for each request: $host, $uri, $remote_addr, $scheme. The full list is in the alphabetical variable index on the documentation site; the common ones are collected in the cheat sheet.
Checking and reloading
bashcheck the configuration
nginx -t
nginx -t checks the syntax and tries to open the files the configuration refers to, such as certificates, logs and directories. nginx -T does the same and also prints the entire resulting configuration with all included files, which is handy for finding where a directive comes from.
bashapply the configuration without stopping
nginx -t && nginx -s reload
On a reload, the master process first checks the syntax and tries to open the logs and sockets; if something cannot be opened, it rolls back and keeps running with the old configuration. So an error in the config does not stop the site, but it does not apply the edit either; you can see it in the output of nginx -t.
One nginx instance can serve several sites on the same address and port. Each site has its own server block, and nginx picks the block by the connection’s address and port, then by the name in the Host header. For what goes inside a block, see the sections “Configuration: contexts and directives” and “Location blocks and static files”.
Selection takes two steps. First, nginx compares the request’s address and port with the listen directives; every block whose address:port pair matches is a candidate. Then, among those, it looks for the block whose server_name includes the name from the Host header. The default server belongs to an address:port pair, not to a name.
nginxnginx.conf: two sites and a catch-all on one port
server { listen 443 ssl; listen [::]:443 ssl; server_name blog.example.com; ssl_certificate /etc/nginx/ssl/example.com.pem; ssl_certificate_key /etc/nginx/ssl/example.com.key; root /var/www/blog;}server { listen 443 ssl; listen [::]:443 ssl; server_name shop.example.com; ssl_certificate /etc/nginx/ssl/example.com.pem; ssl_certificate_key /etc/nginx/ssl/example.com.key; root /var/www/shop;}# catch-all for every other name on this portserver { listen 443 ssl default_server; listen [::]:443 ssl default_server; server_name ""; ssl_certificate /etc/nginx/ssl/example.com.pem; ssl_certificate_key /etc/nginx/ssl/example.com.key; return 444;}
IPv4 and IPv6 use separate listening sockets, so each block has two listen directives: one for 443 ssl and one for [::]:443 ssl. The [::] socket accepts IPv6 connections only, because the ipv6only parameter is on by default. If there is no listen directive at all, nginx listens on *:80 when run as superuser or *:8000 otherwise.
How nginx chooses a server block
Among the blocks with a matching address:port pair, the name from the Host header is compared with server_name from the most specific kind of name to the least, and the search stops at the first match. What decides specificity is the type of name, not the order in the file.
Priority
Name type
Example
1
exact name
shop.example.com
2
longest wildcard with a leading asterisk
*.example.com
3
longest wildcard with a trailing asterisk
mail.*
4
first matching regular expression
~^shop\.
5
default server
—
An asterisk can appear only at a dot boundary, and it stands for several name parts at once: *.example.com matches both shop.example.com and shop.sub.example.com. The form .example.com is shorthand for the exact name together with the wildcard *.example.com. Regular expressions start with a tilde and are tested in the order they appear in the file.
A request to 203.0.113.10:443 with Host: shop.example.com matches the exact name shop.example.com from the configuration above, so wildcards and regexes are never reached.
Default server and the catch-all
If the name matches no block, or the request has no Host header at all, the default server for that address:port pair handles it. This is the block whose listen contains default_server; if no block has that parameter, it is the first block with that pair in the file. One port can have several addresses, and each has its own default server.
Code 444 is a non-standard nginx code: it closes the connection without sending a response. The name _ seen in many configurations online is not special: it is simply an invalid domain that will never match a real name, and -- or !@# would work just as well. There is no catch-all name; the default server is set by the default_server parameter of listen, not by server_name.
By default a server block has an empty server_name, so server_name "" is enough for the catch-all, and it catches requests with no Host header (before 0.8.48 the machine’s hostname was used instead of an empty name). If a block that is not the default server must also handle requests without Host, add "" to its list of names.
Two sites on one IP: the reference example
A typical setup: one address, two sites, HTTPS, and a redirect from www.example.com to shop.example.com. A separate block on port 80 catches HTTP and redirects to HTTPS; the redirect target uses $host, as in the cheat sheet, rather than a hard-coded name.
$host is taken in this order: the name from the request line, then the Host header, then the name of the matching server. That is why the port 80 block sends the client to HTTPS on the site it actually asked for. $request_uri is the full original URI with arguments, not decoded, so the path and parameters survive the redirect unchanged.
Choosing between an exact name, a wildcard and a regular expression
Name type
When to use
Example
exact name
the main site; lookup is fastest
example.com
.example.com
the exact name and all subdomains at once
.example.com
*.example.com
subdomains matching a pattern
*.example.com
mail.*
a group of names with a common start
mail.*
regular expression
a pattern a wildcard cannot express
~^www\d+\.
empty name
catch-all for requests without Host
""
Exact names and both forms of wildcard are kept in three hash tables bound to the listening port. Looking them up is faster than trying regular expressions one by one, which is the slowest method. If a site is most often requested as example.com and www.example.com, list those as exact names and put any wildcard last.
In more detail
The server block is determined in several stages: during the TLS handshake, by SNI, before the HTTP request is read; after the request line is parsed; and after the Host header is parsed. The configuration can change at each stage, so some directives reliably take effect only in the default server: a TLS session is always resumed from it, which applies to ssl_session_cache, ssl_session_timeout and ssl_early_data.
Certificates and ciphers for these blocks are covered in the section “HTTPS and TLS”. What goes inside a block (path handling, static files and proxying) is covered in the section “Location blocks and static files”.
A location block inside server defines how nginx handles URIs that start with a given path, from serving files to proxying. For each request nginx picks one location: exact matches and prefixes first, then regular expressions. File paths are directed by root, alias and try_files.
The reference example is a typical static site: a single-page application with an index.html entry point, long-lived caching for built assets and an exact match for a liveness check. Each technique in it is explained separately below.
nginxnginx.conf: a static site with an SPA
server { listen 80; server_name example.com; root /var/www/site; index index.html; # SPA: no such file, serve index.html location / { try_files $uri $uri/ /index.html; } # ^~ disables regular expressions for assets location ^~ /static/ { expires 30d; } # images by extension, cached for a week location ~* \.(png|jpg)$ { expires 7d; } # exact match for the liveness check location = /healthz { return 200 "ok\n"; }}
How nginx chooses a location
Entry
What it matches
Notes
location = /page
the exact URI, without arguments
the search ends immediately
location /page/
a URI prefix
the longest one is remembered
location ^~ /page/
a URI prefix
regular expressions are not checked
location ~ \.php$
a case-sensitive regular expression
the first match in the file
location ~* \.php$
a case-insensitive regular expression
the first match in the file
location @fallback
a named location
internal redirects only
The order is as follows. Among the prefix locations, nginx finds the longest matching prefix and remembers it. It then checks the regular expressions in the order they appear in the file, and uses the first one that matches. If none match, the remembered prefix handles the request. An = match ends the search at once, which is why location = / speeds up handling of frequent requests for the root.
Without ^~, the regular expression for images would win over the prefix.
root and alias
root sets the directory to which the whole request URI is appended: root /var/www/site turns /static/logo.png into the file /var/www/site/static/logo.png. alias replaces the matched part of the location with its own path: with alias /data/w3/images/, /img/top.gif becomes /data/w3/images/top.gif. The value of both directives can contain variables.
nginxroot appends the URI, alias replaces the prefix
Watch your slashes: the rest of the URI is appended to the alias value without any checks, so location /img/ with alias /data/files and no trailing slash looks for /img/a.png as /data/filesa.png. When the end of the location matches the end of the alias value, the documentation advises replacing the pair with root: location /images/ with root /data/w3 serves the same files as alias /data/w3/images/. Inside a regular expression location, alias gives the full file path and usually relies on a capture from the expression:
nginxalias with a capture from a regular expression
# alias inside a regex location: the full pathlocation ~ ^/files/(.+)$ { alias /data/files/$1;}
try_files, index and error_page
try_files goes through its candidates and takes the first one that exists; the path for each is built from the root or alias of the current context. $uri is a file with that path, $uri/ is a directory (so index applies), and the last parameter says what to do if nothing was found: a URI for an internal redirect, =404 for a response code, or @backend for a named location. For an SPA the last parameter is /index.html, so any unknown path serves the entry point.
nginxan SPA entry point and a 404 page
# SPA: serve the file or directory if it exists, else index.htmllocation / { try_files $uri $uri/ /index.html;}# a custom 404 page instead of the default oneerror_page 404 /404.html;
nginx treats a request with a trailing slash as a request for a directory: index lists the candidate files, index.html by default, and passes the request by internal redirect to the first one that exists. That request may land in a different location, such as ~ \.php$ for FastCGI. error_page assigns a URI to errors: error_page 404 =200 /empty.gif serves the file with code 200, and error_page 404 = @fallback hands processing to a named location without changing the code. A request can go through at most 10 internal redirects; after that nginx returns 500 and writes rewrite or internal redirection cycle to the error log.
return and rewrite
return stops processing and answers the client immediately with a code, a code with text, or a redirect (301, 302, 303, 307, 308). Code 444 closes the connection without a response. rewrite changes the URI using a regular expression: the last flag restarts the location search for the new URI, break continues processing in the current location, and redirect and permanent return 302 and 301. In a server block, the directives of this module run before a location is chosen.
nginxa section redirect and an internal rewrite
# the section has moved: old links get a 301rewrite ^/blog/(.*)$ /news/$1 permanent;# change the URI and choose a location againlocation /docs/ { rewrite ^/docs/(.*)$ /help/$1 last;}
Serving static files: speed and directory listings
sendfile on sends a file with the sendfile() system call, without copying it through an nginx buffer. sendfile_max_chunk 1m limits a single call so that one fast client cannot occupy a worker process entirely. tcp_nopush on sends the response headers and the start of the file in one packet. expires adds the Expires and Cache-Control fields to the response: use a long period for immutable assets and a short one for files that change often. autoindex on enables a generated listing of a directory’s files when index finds no index file; on public sites it is kept off so as not to expose the directory structure.
Proxying requests to an application, and named locations as a fallback, are covered in the section “Reverse proxy”. Common configuration error messages are covered in the section “Common errors and troubleshooting”.
A reverse proxy is a mode in which nginx accepts client requests and passes them to an application using the proxy_pass directive. The application does not know client addresses, so nginx passes them in headers set with proxy_set_header.
Clients talk only to nginx, which terminates TLS and sits in front of an application listening on a local address such as 127.0.0.1:8000. The application learns the site name and the client address only from the headers nginx adds.
The request reaches the application, and the response returns along the same path.
The reference example: nginx in front of an application
This is how nginx is placed in front of gunicorn, uWSGI and any other application that listens for HTTP. Without the headers, the application would see 127.0.0.1 (nginx’s own address) as the client address and 127.0.0.1:8000 in Host, because by default nginx replaces Host with the name from proxy_pass and does not pass the original Host and Connection.
Where the request path goes
proxy_pass takes a scheme, an address and an optional URI. Whether a URI is present at the end determines what the application receives in place of the request path.
proxy_pass in location /api/
Where /api/users goes
http://127.0.0.1:8000
/api/users, the path as the client sent it
http://unix:/run/app.sock
/api/users, the path as the client sent it
http://127.0.0.1:8000/
/users, with /api/ replaced by /
http://127.0.0.1:8000/v2/
/v2/users, with /api/ replaced by /v2/
The URI in proxy_pass replaces the matched part of the location; without a URI the path is passed as is. If the location is defined by a regular expression, or is a named location, write proxy_pass without a URI: there is no way to tell which part of the path to replace.
Headers the application sees
Header
Value
What the application learns
Host
$host
the site name the request came in on
X-Real-IP
$remote_addr
the client address
X-Forwarded-For
$proxy_add_x_forwarded_for
the client address, appended to the chain from previous proxies
X-Forwarded-Proto
$scheme
the scheme of the client request: http or https
A value that is an empty string removes the header from the request, written as proxy_set_header X-Forwarded-For "";. proxy_set_header directives are inherited from an outer level only as a whole: a single directive in a location cancels all the headers from server (see the section “Configuration: contexts and directives”).
A client can send the X-Forwarded-For header itself, so trust it only if requests come from your own proxies. For the limits of this, see the section “Security and rate limiting”.
Timeouts and response buffering
Directive
Default
What it limits
proxy_connect_timeout
60s
establishing the connection to the application; usually cannot exceed 75 s
proxy_read_timeout
60s
the pause between reads of the response: if the application is silent, the connection is closed
proxy_send_timeout
60s
the pause between writes of the request to the application
proxy_buffering
on
collecting the response in buffers before sending it on
Timeouts are measured between two consecutive operations, not over the whole response: an application can respond for hours as long as it sends data more often than once a minute. With buffering on, nginx pulls the response from the application into its own buffers as fast as it can and hands it to the client at the client’s pace. With off, the response goes to the client synchronously, so a slow client keeps the application’s worker busy.
How to proxy WebSocket
Switching to WebSocket relies on the Upgrade and Connection HTTP headers, which are not passed to the application automatically: nginx must pass them explicitly and talk to the application over HTTP/1.1.
nginxswitching to WebSocket with Upgrade
# the map block goes in the http contextmap $http_upgrade $connection_upgrade { default upgrade; '' close;}location /ws/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;}
map turns an empty Upgrade into close and a non-empty one into upgrade, so the Connection header adapts to the request. Ordinary requests proceed without a protocol switch, and upgrade requests get a tunnel. Since version 1.29.7 nginx talks to the application over HTTP/1.1 by default; in older branches, add proxy_http_version 1.1;. The tunnel is closed if the application sends no data for longer than proxy_read_timeout; for long-lived connections, increase it or set up WebSocket ping frames.
An application behind a Unix socket
If the application is on the same host, TCP is not needed: the address in proxy_pass can point to a Unix socket.
The socket path comes after the word unix, and after the second colon comes an optional URI with the same path replacement rules. PHP-FPM uses a different protocol, FastCGI, with its own fastcgi_pass directive and fastcgi_param settings in the ngx_http_fastcgi_module module.
Several applications behind one name, and choosing a server based on failures, are covered in the section “Load balancing”; response caching in “Caching and compression”; and HTTPS on the client side in “HTTPS and TLS”.
Load balancing is the distribution of requests among several instances of an application. nginx takes a list of servers from an upstream block and sends each next request to the next one; when a server fails, it passes requests to the others.
A group of servers is defined by an upstream block in the http context, and requests are directed to it by proxy_pass with the group’s name. A single directive selects the distribution method: by default requests go round-robin, and the alternatives are least_conn, hash and ip_hash. nginx checks server health passively, based on the outcome of its own attempts.
nginxthe reference example: a group of three servers
http { upstream app { server 192.0.2.10:8000; server 192.0.2.11:8000; server 192.0.2.12:8000; } server { listen 80; location / { proxy_pass http://app; } }}
In proxy_pass the group name takes the place of the host: http://app. FastCGI, uwsgi, SCGI, memcached and gRPC have their own directives: fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass and grpc_pass. The address in server can be a domain name or a Unix socket.
Distribution methods
The method is set by a directive inside upstream and applies to the whole group. Without a directive, round-robin is used: requests go to the servers in turn, taking weights into account. If requests differ in duration, least_conn distributes more fairly, picking the server with the fewest active connections.
Method
How it picks a server
Directive
Round-robin
each request goes to the next server
none (default)
Least connections
the server with the fewest active connections
least_conn
By client IP
a hash of the client address
ip_hash
By arbitrary key
a hash of variables, such as the URI or a cookie
hash $…
By response time
the server with the lowest average response time
least_time
least_time picks a server by average response time. In open source it appeared in mainline 1.31.0 and is not in the 1.30 branch.
The ip_hash and hash directives pin a client to a server: ip_hash hashes the client’s IP address, and hash hashes any key made of text and variables, such as $request_uri. While the server is available, one client’s requests go to it; if it becomes unavailable, nginx picks another. More flexible pinning with cookies and routes is provided by the sticky directive.
nginxmethod and weights; hash with a key
upstream app { least_conn; server 192.0.2.10:8000 weight=3; server 192.0.2.11:8000; server 192.0.2.12:8000;}upstream cart { hash $cookie_session_id consistent; server 192.0.2.20:8000; server 192.0.2.21:8000;}
The weight weight=N is 1 by default and sets a share of requests: with weights 3, 1 and 1, three of every five requests go to the first server. Weights work with all methods. The consistent parameter of hash reduces how many keys are remapped when the group changes, which matters for caching servers.
Errors and passing a request on
When a server fails, nginx can pass the request to the next one in the group. proxy_next_upstream defines what counts as a failure: by default, a connection error and a timeout; you can add response codes to the list, for example http_502 and http_429. proxy_next_upstream_tries and proxy_next_upstream_timeout limit the number of attempts and the total time spent on them.
A retry is possible only while no byte of the response has been sent to the client. POST, LOCK and PATCH requests are not retried once they have reached a server; the non_idempotent parameter can allow retries, if the application survives a repeated submission.
nginxretrying a request on the next server
location / { proxy_pass http://app; # 502, 503 and 429 also pass the request to the next server proxy_next_upstream error timeout http_502 http_503 http_429; proxy_next_upstream_tries 2; proxy_next_upstream_timeout 5s;}
Passive health checks
nginx does not send probe requests to servers: it judges health from its ordinary attempts. max_fails counts consecutive failed attempts (1 by default), and fail_timeout sets the window and the quarantine period (10 s by default); max_fails=0 turns the counting off.
If a server accumulates max_fails failures within fail_timeout, it is excluded from distribution for the same period. nginx then brings it back carefully: it tries it with live client requests and, on success, starts distributing to it again.
Each worker process keeps its own failure counter unless the group has a zone.nginxa failure threshold and a backup server
upstream app { server 192.0.2.10:8000 max_fails=3 fail_timeout=30s; server 192.0.2.11:8000 max_fails=3 fail_timeout=30s; # a standby server for when the primary ones are unavailable server 192.0.2.12:8000 backup;}
The backup parameter keeps a server in reserve while the primary ones are available and brings it in when none are left. The down parameter excludes a server from distribution entirely: this is how you mark an instance being retired without deleting its line.
What counts as a failure for max_fails is defined by proxy_next_upstream: the codes http_500, http_502 and http_429 are counted only if they are named in the directive, while http_403 and http_404 are never counted.
Keepalive connections to the upstream
Requests can reuse connections to the upstream: the keepalive directive in an upstream block enables a cache of idle connections, so nginx does not open a new TCP connection for every request. Since 1.29.7 the cache is on by default and holds up to 32 connections per worker process; a number in the directive sets your own limit.
keepalive limits the number of idle connections in the cache, not the total number of connections to the upstream, so set it small enough for the upstream to accept new connections. For HTTP you need protocol 1.1 or higher (the default since 1.29.7) and an empty Connection header; for FastCGI you need fastcgi_keep_conn turned on.
nginxa connection cache to the upstream
upstream app { server 192.0.2.10:8000; server 192.0.2.11:8000; keepalive 32;}server { listen 80; location / { proxy_pass http://app; # for versions before 1.29.7: # proxy_http_version 1.1; # proxy_set_header Connection ""; }}
What only NGINX Plus offers
Active health checks are periodic requests to a dedicated path that take a server out of service based on the response code. They exist only in the commercial NGINX Plus subscription, as does the gradual server ramp-up slow_start. In open source, health is checked only passively, and session persistence is available through the sticky directive (since 1.29.6).
TCP and UDP in stream
The same upstream blocks work in the stream context, where nginx balances TCP and UDP: proxy_pass inside a server block of the stream context directs the connection or datagram. The methods are the same: round-robin, least_conn and hash; max_fails and fail_timeout handle the quarantine.
nginxTCP balancing in stream
stream { upstream pg { least_conn; server 192.0.2.10:5432 max_fails=3 fail_timeout=30s; server 192.0.2.11:5432 max_fails=3 fail_timeout=30s; } server { listen 5433; proxy_pass pg; }}
The stream module is not part of the default build: it is enabled with the --with-stream parameter, and Linux distributions often ship it as a separate package. Passing a TCP connection on after a failure is enabled by proxy_next_upstream from the stream module (on by default), which takes only the values on and off.
In more detail
The group’s state is shared between worker processes by the zone directive; without it, each worker process counts failures on its own. The resolve parameter enables DNS names with change tracking, and max_conns sets the limit of simultaneous connections to a server. The error log tells you which server did not respond and why.
For related topics, see response caching in the section “Caching and compression” and server block selection in the section “Server blocks and server selection”.
Caching is a mode in which nginx stores application responses in a cache on disk and serves a copy itself on repeat requests, without passing them to the application. Compression (gzip) shrinks a response by half or more before it is sent. Both are enabled with configuration directives.
Both mechanisms take load off the site, but in different places: the cache removes application work and database queries, compression reduces traffic between nginx and the reader. For a page that is the same for every visitor, the cache gives the biggest gain; for responses with a session cookie, caching does harm, while compression still helps.
How to enable the cache
The cache is defined by the proxy_cache_path directive in the http context: a path on disk, the name and size of a shared memory zone, how long an entry may go unaccessed, and a size limit. The zone name is passed to proxy_cache in the relevant location, and responses there are now cached; proxy_cache_valid sets how long they are kept.
The keys_zone size does not limit the data itself: the zone holds only keys and file metadata, and one megabyte fits about 8,000 keys. The data limit is set by max_size; the cache manager process enforces it and removes the entries that have gone unaccessed the longest. Entries not accessed for longer than inactive are removed regardless of freshness; the default is 10 minutes. levels spreads files across subdirectories: the file name is the MD5 of the cache key.
proxy_cache_path parameter
What it sets
path
the directory on disk where cache files are stored
keys_zone
the zone name and its memory for keys, for example app_cache:10m
inactive
remove an entry not accessed for this long; the default is 10 minutes
max_size
the limit on the cache size on disk
levels
subdirectories made from characters of the file name, for example levels=1:2
Cache key and lifetime
The cache key is built from request variables by the proxy_cache_key directive; by default it is roughly $scheme$proxy_host$uri$is_args$args. The key ignores cookies, so different users get the same copy. That suits shared pages and breaks personalised ones. GET and HEAD requests are cached, and proxy_cache_methods sets the list of methods; POST is not cached by default, and if you add it to the list, include the method in the key: $scheme$proxy_host$request_method$uri$is_args$args.
nginxnginx.conf: key and lock
location /posts/ { proxy_cache app_cache; # GET and HEAD give the same response, so the key has no method proxy_cache_key $scheme$proxy_host$uri$is_args$args; proxy_cache_valid 200 10m; proxy_cache_valid any 1m; proxy_cache_lock on; # if the application fails, serve a stale copy proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;}
proxy_cache_lock on lets only the first request for a new key through to the application; the rest wait for the entry to appear in the cache. Without it, a thousand simultaneous requests fill the cache with a thousand identical hits on the application. proxy_cache_use_stale lists the cases when a stale copy is better than an error. proxy_cache_revalidate on makes refreshing cheaper: nginx asks the application with If-Modified-Since and If-None-Match, and an unchanged response extends the entry’s lifetime without transferring the body.
Cache status: HIT, MISS, EXPIRED, BYPASS
The $upstream_cache_status variable shows how the cache lookup ended for a given response. Add it to a response header and check it in the browser developer tools or in the access_log.
Value
What happened
HIT
the response was served from the cache; the application was not called
MISS
there was no entry in the cache; the response came from the application
EXPIRED
the cache entry had expired; nginx refreshed it from the application
BYPASS
a proxy_cache_bypass condition sent the request past the cache
STALE
a stale copy was served because of proxy_cache_use_stale
UPDATING
a copy was served while a new one is being fetched in the background
REVALIDATED
If-Modified-Since confirmed that the body had not changed
nginxnginx.conf: cache status
location / { proxy_cache app_cache; # cache lookup status for this response add_header X-Cache-Status $upstream_cache_status;}
What not to cache
For pages behind a login, a condition in proxy_cache_bypass disables reading from the cache, and the same condition in proxy_no_cache disables storing the response: if any parameter is non-empty and not equal to “0”, the restriction applies. Session cookies still reach the application, because nginx passes the client’s request headers by default.
nginxnginx.conf: location behind a login
location /account/ { proxy_pass http://app; proxy_cache app_cache; # private pages are always requested from the application proxy_cache_bypass $cookie_session; proxy_no_cache $cookie_session;}
gzip compression
The gzip filter is off by default; gzip on enables compression, and gzip_types adds response types beyond text/html, which is always compressed. gzip_min_length skips small responses that are not worth compressing; gzip_comp_level, from 1 to 9, trades speed for size, and the default is 1.
nginxnginx.conf: response compression
http { gzip on; gzip_min_length 1000; gzip_comp_level 5; gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml; # CDNs and browser caches see that both gzip and plain versions exist gzip_vary on;}
Types are given as the response MIME type: values such as css or js do not work here. Compression is applied only if the client asked for it with the Accept-Encoding header. gzip_vary on adds the Vary: Accept-Encoding field to the response; without it, an intermediate cache between nginx and the reader, such as a CDN, may serve a compressed copy to a client that did not ask for gzip.
Caching headers for static files
The expires directive adds Expires and Cache-Control fields to the response: a positive time produces Cache-Control: max-age with that value, a negative one produces Cache-Control: no-cache. For files that never change (a version or hash in the name), set a long lifetime; for other static files, a short one.
nginxnginx.conf: a month in the cache
location ~* \.(css|js|png|woff2)$ { expires 30d;}
If the application sends caching headers, they take precedence over nginx directives: X-Accel-Expires sets the cache lifetime in seconds, zero disables caching, and Expires and Cache-Control from the response apply instead of proxy_cache_valid. This lets the application control the proxy cache without changing the nginx configuration.
In more detail
Instead of proxy_cache_use_stale, the application can allow stale copies itself with the Cache-Control extensions stale-while-revalidate, while the copy is being refreshed, and stale-if-error, on an error. Caching header semantics are covered in full in the HTTP and REST reference, in the “Caching” section.
HTTPS in nginx is enabled with the ssl parameter of the listen directive, a certificate in ssl_certificate and a key in ssl_certificate_key. HTTP/2 (the http2 on directive) and HTTP/3 (the quic parameter of listen) run on the same port 443, and a Let’s Encrypt certificate can be issued by nginx itself through the ngx_http_acme_module module.
nginx handles TLS termination itself: it decrypts the request and passes plain HTTP to the application. The application needs no certificate; it sees ordinary requests from a local proxy. Cipher suites and the choice of TLS versions are covered in the “TLS and PKI” reference; this section covers the nginx directives.
A minimal HTTPS server
The ssl parameter of listen makes the port accept TLS connections; the ssl_certificate and ssl_certificate_key directives point to the certificate and key files in PEM format. server blocks and selection by server_name are covered in the “Server blocks and server selection” section.
The ssl_certificate file must hold the full certificate chain: the server certificate first, followed by the intermediate certificates of the certificate authority. If you do not send the intermediates, the site opens in browsers but breaks for older clients and APIs that do not build the chain themselves. The key may live in the same file as the certificate; only the certificate is sent to the client. The directive can be given several times to load certificates of different types: RSA and ECDSA.
Protocol versions are set by ssl_protocols. By default nginx (since 1.27.3) uses TLSv1.2 and TLSv1.3, so you usually do not need to configure it explicitly. Which TLS versions and cipher suites to recommend is covered in the “TLS and PKI” reference, in the “Security” section.
Sessions and tickets
The handshake is the most expensive part of a TLS connection. To avoid repeating it for every connection, nginx can resume sessions: the parameters are kept either in a cache shared between worker processes (ssl_session_cache) or in an encrypted ticket held by the client (a TLS session ticket, ssl_session_tickets).
session cache: shared:SSL:10m is 10 MB shared by all worker processes
ssl_session_timeout
5m
how long a client can reuse session parameters
ssl_session_tickets
on
resumption through a TLS session ticket
One megabyte of the shared cache holds about 4,000 sessions. Turn ssl_session_tickets off when ticket keys cannot be rotated regularly; the trade-off is discussed in the “TLS and PKI” reference.
HTTP/2 and HTTP/3
HTTP/2 is enabled with the http2 on directive in a server block, usually together with TLS: browsers use HTTP/2 only over TLS, although nginx also supports it over plain TCP (h2c).
HTTP/3 runs over QUIC (UDP), so the listen directive has a quic parameter, provided by the ngx_http_v3_module module since version 1.25.0. With several worker processes, add reuseport. Keep an ordinary ssl listener on the same port alongside it: clients start with HTTP/1.1 or HTTP/2 and learn about HTTP/3 from the Alt-Svc header, which you add with add_header, as in the documentation example.
The ngx_http_acme_module module runs ACMEv2 (Automatic Certificate Management Environment, RFC 8555) itself: it obtains a certificate from the issuer, renews it, and supplies it to ssl_certificate through the $acme_certificate and $acme_certificate_key variables. The nginx-module-acme package with the module is available since version 1.29.0.
nginxnginx.conf: nginx issuing its own certificate
resolver 127.0.0.1:53;acme_issuer example { uri https://acme.example.com/directory; contact admin@example.com; state_path /var/cache/nginx/acme; accept_terms_of_service;}acme_shared_zone zone=ngx_acme_shared:1M;server { listen 443 ssl; server_name example.com; acme_certificate example; ssl_certificate $acme_certificate; ssl_certificate_key $acme_certificate_key; ssl_certificate_cache max=2;}# port 80 is needed for the http-01 challengeserver { listen 80; location / { return 404; }}
The block on port 80 is required: by default the module completes the http-01 challenge, and the issuer comes for the token on port 80. The alternative is an external client such as certbot: it renews the certificate itself and puts the files on disk, and nginx only reads them through ssl_certificate.
HSTS and the add_header trap
Strict-Transport-Security (HSTS) is a header that tells the browser to visit the site only over HTTPS, even for http:// links. Set it with add_header and the always parameter so the header is also sent with error responses.
Start with a small max-age and raise it once you are sure all subdomains work over HTTPS: the browser remembers the header for a long time, and visitors find it hard to roll back. The header is covered in detail in the “TLS and PKI” reference, in the “Security” section.
Several HTTPS sites on one IP
Several HTTPS servers can run on one IP address and port 443: the client sends the site name in the handshake through the TLS SNI (Server Name Indication) extension, and nginx selects the certificate by name, just as it selects the server block. In TLSv1.3, SNI support is mandatory.
Outdated clients without SNI get the server’s default certificate.
The default server for port 443 receives clients that did not send a name. To drop such connections immediately, enable ssl_reject_handshake on in it. The obsolete ssl on directive was removed in version 1.25.1; only the ssl parameter of listen works.
nginxnginx.conf: rejecting clients without SNI
server { listen 443 ssl default_server; ssl_reject_handshake on;}
Protecting an nginx server comes down to five techniques: limiting the request rate and the number of connections per client, access by address and password, hiding the version, limiting uploads, and blocking dangerous paths. The key directives are limit_req, limit_conn, allow, deny and auth_basic.
Rate limiting
Rate limiting is provided by the ngx_http_limit_req_module module using the leaky bucket algorithm: requests above the zone’s rate are delayed, and once the burst buffer is full they are rejected. The zone is defined by limit_req_zone in the http context and applied by limit_req:
nginxnginx.conf: at most 10 requests per second per address
The $binary_remote_addr key is the compact client address: 4 bytes for IPv4 and 16 bytes for IPv6. One state takes 64 bytes on 32-bit platforms and 128 bytes on 64-bit ones, so a 10 MB zone holds about 80,000 states. The rate is measured in r/s or r/m: 30r/m is one request every two seconds.
The burst parameter allows a short spike above the rate: nginx delays the excess requests and rejects them once the burst is full. Delay usually hurts real users, so add nodelay: burst slots are used up immediately and excess requests are rejected without waiting.
Parameter
What it does
Default
rate=10r/s
the average rate in the zone
none; always required
burst=20
the size of the burst queue
0; all excess is rejected
nodelay
a burst without delays inside burst
permitted requests are delayed
delay=5
the first 5 excess requests are not delayed, later ones are
0; all are delayed
limit_req_status 429
the response code for rejected requests
503
A rejected request gets 503; limit_req_status changes the code, for example to 429 (Too Many Requests). Pick the threshold in limit_req_dry_run on mode: nginx rejects nothing but counts the excesses. Several limit_req directives apply at the same time, so you can limit both the client address and the server as a whole ($server_name in the key).
Other variables can go into the zone key too, such as the URI, the site name or a cookie; requests with an empty key are not counted.
Limiting the number of connections
The ngx_http_limit_conn_module module counts connections by a key, usually the client address. A connection is counted only while it has a request being processed whose headers have been fully read; in HTTP/2 and HTTP/3 each parallel request counts as a separate connection.
nginxnginx.conf: at most 4 connections per address
Above the limit, nginx responds with the code from limit_conn_status (503 by default); idle keep-alive connections are not counted. The directives of both modules are inherited from the previous level only if the current level has none at all.
Access by address and password
The allow and deny rules of the ngx_http_access_module module are checked in order until the first match; a deny all rule at the end turns the list into an allowlist. Below, the admin area is closed to everyone except the office network:
A password is added by the ngx_http_auth_basic_module module: the auth_basic directive enables HTTP Basic Authentication, and auth_basic_user_file points to a file of name:password pairs. Create passwords with the htpasswd utility or the openssl passwd command; the {PLAIN} and {SHA} schemes are insecure, so use apr1 or crypt() for new passwords.
nginxa password-protected section
# the password file is created by htpasswdlocation /staging/ { auth_basic "closed site"; auth_basic_user_file /etc/nginx/.htpasswd;}
By default satisfy all requires both a permitted address and a password; satisfy any requires either one. You can skip the password for your own networks. The password travels in clear text, so such a section must work only over HTTPS (see the “HTTPS and TLS” section).
Reducing the attack surface
The server_tokens off directive removes the nginx version number from the Server field and from the standard error pages. It is no defence against a targeted attack, but it removes a hint for picking an exploit for a specific version.
nginxin the http context
server_tokens off;
Large request bodies are another source of problems. client_max_body_size is 1m by default: a large upload gets a 413, and a deliberately huge body is never proxied to the application. Set an explicit limit: a general one at the server level and a separate one for uploads in their own location:
nginxnginx.conf: a general limit and a separate one for uploads
server { client_max_body_size 1m; location /upload/ { client_max_body_size 20m; }}
A slow client is also a load: by trickling in a header or body for minutes, it ties up a worker process. The client_header_timeout and client_body_timeout timeouts (60s by default) end a silent request with a 408: the header must arrive in full, while for the body the timeout is counted between two chunks of data, not for the whole transfer. limit_rate caps the response speed in bytes per second.
nginxnginx.conf: hidden and internal files
# block hidden files and directorieslocation ~ /\. { deny all;}# do not serve editor backup fileslocation ~ \.(bak|old|swp)$ { deny all;}
The regular expression ~ /\. blocks paths where a dot follows a slash: .git, .htaccess, .env. Hidden files stay in the directory and are served like any other until you forbid them. Symbolic links in paths are checked by disable_symlinks if_not_owner: a file will not open if any component of the path is a link whose owner differs from the owner of its target.
Bad and good
Bad
Why it is dangerous
Good
location /img { alias /data/; }
/img../etc/passwd reads files outside the site root
location /img/ { alias /data/; } with a trailing slash on the location
proxy_pass for everything without limits
one client ties up the application with requests and connections
limit_req and limit_conn in front of the proxy
auth_basic without HTTPS
the password travels in clear text
listen 443 ssl first, then the password
no client_max_body_size at the server level
the default of 1m breaks uploads, and the application may have no limit of its own
an explicit limit: a general one and a separate one for uploads
autoindex on; for the whole site
visitors see directory listings
autoindex only in the locations that need it
For more on alias, see the “Location blocks and static files” section; for passing requests to the application, see “Reverse proxy”. You can restrict the set of methods with a limit_except block: limit_except GET { deny all; } forbids everything except GET (HEAD is allowed along with it).
Diagnosis runs from the configuration to the logs. nginx -t checks syntax and paths, error.log explains why nginx does not start or returns 502, and access.log with the $upstream_status variable shows what the application replied.
Order of checks
nginx -t: configuration syntax, and opening the files it refers to;
systemctl status nginx: whether the service is running, if it is started by systemd;
error.log: startup and proxying errors, with the text of the system error;
access.log with $status and $upstream_status: what the client received and what the upstream server returned;
curl -v: the same request the client makes, with connection details.
nginx -V prints the log paths (the --error-log-path and --http-log-path options), and error_log sets the log level: error by default, while warn adds warnings. The levels are debug, info, notice, warn, error, crit, alert and emerg; a chosen level also includes all the more serious ones.
nginxnginx.conf: log level
error_log /var/log/nginx/error.log warn;
nginx does not start
At startup nginx opens ports and logs and reads the configuration. systemd shows the reason for a failure in the service status, and error.log gives the details:
The most common case is a port taken by another process: nginx writes to error.log that it could not open the port, and systemd restarts the service again and again. ss shows who is listening on the port; see the “Linux” reference, in the “Networking: ip, ss and configuration” section. The fix is to stop the other process or move the server to a different port in the listen directive. The second common case is a typo in the configuration: nginx -t reports it with the file and line: nginx: [emerg] unknown directive "upstraem" in /etc/nginx/conf.d/app.conf:12.
bashwho is holding port 80
sudo ss -ltnp 'sport = :80'
502 Bad Gateway
nginx is running but the application is not: the connection was not established, timed out, or was closed by the application. The error.log entry names the address and the system error:
“Connection refused” means that nothing is listening on the upstream address: the application is not running. Another case is a wrong port or address: the process inside a container listens on 127.0.0.1, while nginx connects to it from another host. Check the address with the same request nginx makes, and compare it with proxy_pass. The failure of one server in an upstream group is not yet a 502: by default nginx passes the request to the next one, via the error and timeout parameters of proxy_next_upstream. The client sees a 502 only when there is nobody left to answer. error_page 502 /50x.html; substitutes your own page for the standard one; the response code stays 502.
The application is slow: more than proxy_read_timeout (60s by default) passed between two reads of the response, so the connection is closed and the client gets a 504. The timeout counts pauses, not the whole response: a long report that the application sends in pieces fits within a minute.
textexample error.log entry
upstream timed out (110: Connection timed out) while reading response header from upstream, client: 203.0.113.7, server: example.com, request: "GET /reports/ HTTP/1.1", upstream: "http://192.0.2.10:8000", host: "example.com"
If the application really must think for longer than a minute, raise the timeout in the block that does the proxying: location /reports/ { proxy_read_timeout 300s; }. Connection setup has its own timeout, proxy_connect_timeout, which usually does not exceed 75 seconds.
413 Request Entity Too Large
The request body is larger than client_max_body_size, which is 1m by default. A 3 MB file upload gets a 413 before it reaches the application. The directive works at the http, server and location levels; a value of 0 disables the check. If the 413 comes from the application rather than nginx, the application has its own limit: compare $upstream_status and $status in the access log.
nginx found the directory but could not serve the file. error.log shows the reason: file or directory permissions keep the worker processes out, so check user and the file owner. Another cause is a directory request that matched none of the files in index.
bashpermissions and directives from the final config
When none of the index files exists, nginx returns 403, or a directory listing if autoindex is on. Access by address also returns 403: the allow and deny rules are covered in the “Security and request limiting” section. A password check returns 401 Unauthorized.
The configuration was not applied
An edit has no effect for two common reasons: you edited a file other than the one nginx reads, or you forgot to reload the configuration. nginx -T prints the final config with all included files, showing which file and which directive nginx is using right now. On reload, the master process first checks the syntax and tries to open logs and sockets. If that fails, it rolls back and keeps working with the old configuration, and the error stays in error.log; the service does not go down.
What the application replied is visible in the $upstream_status, $upstream_addr and $upstream_response_time variables in access.log. log_format in the http context defines the entry format, and access_log attaches the format to a log.
If $upstream_addr lists several comma-separated addresses, nginx tried the servers in turn; $upstream_status repeats them in the same order. If $status differs from the last code in $upstream_status, nginx itself produced the final response, for example with an error_page page.
Debug log
A detailed log at the debug level shows how nginx handles each request, but only if the build was made with --with-debug; you can see this in the output of nginx -V. Linux package builds ship a ready-made nginx-debug binary. You can enable the log for all connections at once with error_log /var/log/nginx/debug.log debug;, or only for selected addresses through debug_connection.
Enable debugging for a short time and only where you are looking for a problem. debug_connection in the events context enables the debug level only for the listed addresses, while other connections log at the error_log level, and error_log memory:32m debug writes the log to memory instead of disk. Overriding error_log without the word debug turns debugging off for that configuration level. The debug log records every operation on every connection: on a busy server it fills the disk quickly and slows things down, so return to the warn or error level once you are done.
This reference covers nginx 1.30, the stable release line. The latest release is 1.30.6, from 14 October 2026. The mainline 1.31 branch gets new features immediately; they reach stable about a year later.
Both branches come from the same code and differ in pace. Mainline is the development line: new releases appear every few weeks and include both fixes and new features. Stable is the production line: it gets releases with bug and vulnerability fixes from the same code, with no new directives.
The branch point is the last mainline release before a new stable cycle.
Branch
Status
Latest release
1.31
mainline, new features
1.31.8 — 21 October 2026
1.30
stable, current
1.30.6 — 14 October 2026
1.28
legacy, 1.30 fixes are not backported
1.28.3 — 24 March 2026
What changed in 1.30
The 1.30 branch split from mainline 1.29.8 in April 2026, so it includes everything added in the 1.29 releases. The highlights for day-to-day work:
Proxying: upstream connections are kept alive (keepalive) by default, proxy_http_version defaults to 1.1, the Connection header is not passed on, and requests to the upstream server can be sent over HTTP/2.
Load balancing: the sticky directive pins sessions to one server; server gained the route and drain parameters.
Headers: add_header inheritance is turned off with add_header_inherit off; the early 103 response (Early Hints) is available through the early_hints directive.
HTTP/3 and QUIC: CUBIC congestion control, 0-RTT with OpenSSL 3.5.1, and the max_headers directive to cap the number of headers.
TLS: certificates, keys and revocation lists are cached at startup and on configuration reload; certificate compression is enabled with ssl_certificate_compression.
The 1.29 cycle also brought backward-incompatible changes: validation of the host name and port in a request now follows RFC 3986, and a bare LF in a chunked body is now an error. For the full list, see CHANGES-1.30 and CHANGES in this section’s sources.
Deprecated and removed
The http2 parameter of listen has been deprecated since 1.25.1: enable HTTP/2 with the http2 on; directive at the server level.
The SSLv2 and SSLv3 protocols are disabled by default; the ssl directive (ssl on;) was removed in 1.25.1 — enable SSL with the ssl parameter of listen.
Security updates
Identifier
What is affected
Fixed in
CVE-2026-15176
Buffer overflow when rewrite changes the URI in a location with alias
1.30.6
CVE-2026-93479
Buffer overflow when evaluating expressions with variables
1.30.6
CVE-2026-95101
HTTP/3: part of an unknown frame ends up in the request body
1.30.6
CVE-2026-97629
TLS session spoofing during session ticket rotation
1.30.6
CVE-2026-97205
Use-after-free with asynchronous I/O and SSI include
1.30.6
CVE-2026-90439
Buffer overflow in HTTP/3 with OpenSSL 3.5.0
1.30.5
CVE-2026-42533
Buffer overflow in map with regular expressions
1.30.4
CVE-2026-42055
Buffer overflow in HTTP/2 and gRPC proxying
1.30.3
CVE-2026-9256
Buffer overflow in rewrite
1.30.2
CVE-2026-42926
HTTP/2: request data injection through proxy_set_body
1.30.1
How to upgrade
Upgrading within the 1.30 branch is safe: the configuration is compatible. On Debian and Ubuntu, install packages from the nginx.org repository; for how to add it, see the section “Installation and first run”. Check the configuration, then update the packages:
bashDebian, Ubuntu
nginx -tsudo apt updatesudo apt install nginx
Reload the configuration with the HUP signal so the new code takes over without dropping connections:
bashsystemd
sudo systemctl reload nginx
nginx -v shows the version. To upgrade without interrupting service, build or obtain the new binary, keep the old one and put the new one in its place, then send signals: USR2 starts a second master process with its workers running the new binary, WINCH gracefully shuts down the old workers, and QUIT stops the old master process.
Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.
Manual edit
reason: manual edit
Manual edit
reason: manual edit
Reference updated
Weekly check
How the reference is checked
Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.
1. Freshness
Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.
2. Errors
Every section is read again: wrong facts, outdated APIs and flags, broken examples.
3. Links — by an HTTP request
Every source link must respond. A broken link is a reason to recheck the section.
No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.
Statuses
Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review