Bookmarks

Nginx

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.

checked 6 Nov · next check 13 Nov · 68 min read

Sections
13
Reading
68 min
Current version
1.30.6
Written from
nginx.org/en/docs

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What nginx is and how it works

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

RoleWhat nginx does
Web serverserves static files over HTTP and HTTPS
Reverse proxyaccepts client requests and passes them to an application: Django and Node.js over HTTP, PHP over FastCGI
Load balancerdistributes requests across several application servers
TLS terminationdecrypts HTTPS and passes plain HTTP to the application over the internal network
TCP/UDP proxyproxies non-HTTP traffic with the stream module
nginxnginx.conf: a site and an API
server {    listen 80;    root /var/www/example.com;     location /api/ {        proxy_pass http://127.0.0.1:8000;    }}

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).

Section sources

the section is written from these pages

Cheat sheet

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.

Management

TaskCommand
Check the configurationnginx -t
Show the configuration with included filesnginx -T
Reload the configuration without stoppingnginx -s reload
Reload the configuration under systemdsudo systemctl reload nginx
Shut down gracefullynginx -s quit
Stop immediatelynginx -s stop
Reopen log filesnginx -s reopen
Version and build optionsnginx -V

Static files

TaskDirective
Directory with the site filesroot /var/www/example.com;
Index file of a directoryindex index.html;
Directory listingautoindex on;
Serve a file or return 404try_files $uri $uri/ =404;
Hide the version in headers and error pagesserver_tokens off;

Proxying

TaskDirective
Pass a request to an applicationproxy_pass http://127.0.0.1:8000;
Pass the site nameproxy_set_header Host $host;
Pass the client addressproxy_set_header X-Real-IP $remote_addr;
Pass the proxy chain with the client addressproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
Pass the request schemeproxy_set_header X-Forwarded-Proto $scheme;
Wait longer for the application’s responseproxy_read_timeout 120s;

TLS

TaskDirective
Redirect HTTP to HTTPSreturn 301 https://$host$request_uri;
Listen for HTTPSlisten 443 ssl;
Certificatessl_certificate /etc/nginx/ssl/example.com.pem;
Certificate keyssl_certificate_key /etc/nginx/ssl/example.com.key;
Minimum TLS versionssl_protocols TLSv1.2 TLSv1.3;
Enable HTTP/2http2 on;
Enable HTTP/3listen 443 quic reuseport;

Limits

TaskDirective
Request body size limitclient_max_body_size 20m;
Rate limiting zonelimit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
Apply the limitlimit_req zone=one burst=5 nodelay;
Connection limiting zonelimit_conn_zone $binary_remote_addr zone=addr:10m;
At most 10 connections per addresslimit_conn addr 10;
Deny an address or networkdeny 203.0.113.0/24;
Allow only your own networkallow 192.168.1.0/24; deny all;
Close the connection without a responsereturn 444;
Password-protect a sectionauth_basic "closed site";
Password fileauth_basic_user_file conf/htpasswd;

Logs

TaskDirective
Access log fileaccess_log /var/log/nginx/access.log;
Disable the access logaccess_log off;
Custom log formatlog_format main '$remote_addr - $request $status';
Error log file and levelerror_log logs/error.log warn;

Common variables

VariableWhat it holds
$hosthost name: from the request line or the Host field
$remote_addrclient address
$request_urioriginal request URI with arguments
$uricurrent normalised URI without arguments
$argsquery string arguments
$schemerequest scheme: http or https
$request_methodrequest method
$statusresponse status code
$upstream_addraddress of the upstream server
$upstream_statusresponse status code of the upstream server

Section sources

the section is written from these pages

Installation and first run

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
bashverify the key
gpg --dry-run --quiet --no-keyring --import \  --import-options import-show \  /usr/share/keyrings/nginx-archive-keyring.gpg
textexample output
pub   rsa2048 2011-08-19 [SC] [expires: 2027-05-24]      573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62uid   nginx signing key <signing-key@nginx.com>
bashon the host, Ubuntu
# 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.

bashon the host, Debian
sudo apt install curl gnupg2 ca-certificates lsb-release \  debian-archive-keyringecho "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \https://nginx.org/packages/debian $(lsb_release -cs) nginx" \    | sudo tee /etc/apt/sources.list.d/nginx.list
bashon the host
sudo apt updatesudo apt install nginx

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.

ini/etc/yum.repos.d/nginx.repo
[nginx-stable]name=nginx stable repobaseurl=https://nginx.org/packages/centos/$releasever/$basearch/gpgcheck=1enabled=1gpgkey=https://nginx.org/keys/nginx_signing.keymodule_hotfixes=true
bashon the host, RHEL
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

PathWhat it holds
/etc/nginx/nginx.confthe main configuration file: a skeleton of contexts
/etc/nginx/conf.d/*.conffiles with server blocks, pulled in by the include directive
/etc/nginx/mime.typesmappings of file extensions to Content-Type headers
/etc/logrotate.d/nginxlog rotation: daily, 52 compressed copies
/usr/share/nginx/htmlthe placeholder page: index.html and 50x.html
/var/log/nginx/access.logaccess log
/var/log/nginx/error.logerror log
/run/nginx.pidprocess 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.

Section sources

the section is written from these pages

Configuration: contexts and directives

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.

ContextWhere it goesWhat it configures
mainoutside all blocksprocesses, the error log, modules, include
eventsin mainconnection handling
httpin maineverything related to HTTP
serverin httpa virtual server: address, port, site names
locationin server or another locationrequests with a matching URI
upstreamin http or streama group of servers for load balancing
streamin mainTCP 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.

nginxmerge headers from the outer level
server {    add_header_inherit merge;    add_header X-Frame-Options DENY;     location /api/ {        add_header Cache-Control no-store;    }}

Main directives in main

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.

DirectiveDefaultWhat it sets
usernobody nobodythe user and group of the worker processes
worker_processes1the number of worker processes; auto uses the number of CPU cores
worker_connections512connections per worker process, in the events block
worker_rlimit_nofile—raises the open file limit so that it covers worker_connections
error_loglogs/error.log errorthe error log file and level
pidlogs/nginx.pidthe 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.

NotationMeaning
1024, 8k, 1mbytes, kilobytes, megabytes
1ga gigabyte: the g suffix is allowed only for offsets
500ms, 30smilliseconds, seconds
10m, 1h, 7dminutes, hours, days
1M, 1ya month is 30 days, a year is 365 days
1h 30ma 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.

Section sources

the section is written from these pages

Server blocks and server selection

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.

PriorityName typeExample
1exact nameshop.example.com
2longest wildcard with a leading asterisk*.example.com
3longest wildcard with a trailing asteriskmail.*
4first matching regular expression~^shop\.
5default 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.

nginxa catch-all as the default server
server {    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;}

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.

nginxnginx.conf: redirect to HTTPS
# HTTP -> HTTPSserver {    listen 80;    listen [::]:80;    server_name shop.example.com www.example.com;     return 301 https://$host$request_uri;}
nginxnginx.conf: the site and the redirect from www
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;} server {    listen 443 ssl;    listen [::]:443 ssl;    server_name www.example.com;     ssl_certificate     /etc/nginx/ssl/example.com.pem;    ssl_certificate_key /etc/nginx/ssl/example.com.key;     return 301 https://shop.example.com$request_uri;}

$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 typeWhen to useExample
exact namethe main site; lookup is fastestexample.com
.example.comthe exact name and all subdomains at once.example.com
*.example.comsubdomains matching a pattern*.example.com
mail.*a group of names with a common startmail.*
regular expressiona pattern a wildcard cannot express~^www\d+\.
empty namecatch-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”.

Section sources

the section is written from these pages

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

EntryWhat it matchesNotes
location = /pagethe exact URI, without argumentsthe search ends immediately
location /page/a URI prefixthe longest one is remembered
location ^~ /page/a URI prefixregular expressions are not checked
location ~ \.php$a case-sensitive regular expressionthe first match in the file
location ~* \.php$a case-insensitive regular expressionthe first match in the file
location @fallbacka named locationinternal 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
# /i/top.gif -> /data/w3/i/top.giflocation /i/ {    root /data/w3;} # /img/top.gif -> /data/w3/images/top.giflocation /img/ {    alias /data/w3/images/;}

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.

nginxsettings for serving large files
# serving large fileslocation /files/ {    sendfile           on;    sendfile_max_chunk 1m;    tcp_nopush         on;}

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”.

Section sources

the section is written from these pages

Reverse proxy

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

nginxan application on the same host, port 8000
server {    listen 80;    server_name example.com;     location / {        proxy_pass http://127.0.0.1:8000;         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;    }}

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

HeaderValueWhat the application learns
Host$hostthe site name the request came in on
X-Real-IP$remote_addrthe client address
X-Forwarded-For$proxy_add_x_forwarded_forthe client address, appended to the chain from previous proxies
X-Forwarded-Proto$schemethe 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

DirectiveDefaultWhat it limits
proxy_connect_timeout60sestablishing the connection to the application; usually cannot exceed 75 s
proxy_read_timeout60sthe pause between reads of the response: if the application is silent, the connection is closed
proxy_send_timeout60sthe pause between writes of the request to the application
proxy_bufferingoncollecting 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.

nginxa socket instead of an address with a port
location / {    proxy_pass http://unix:/run/gunicorn.sock:/;}

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”.

Section sources

the section is written from these pages

Load balancing

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.

MethodHow it picks a serverDirective
Round-robineach request goes to the next servernone (default)
Least connectionsthe server with the fewest active connectionsleast_conn
By client IPa hash of the client addressip_hash
By arbitrary keya hash of variables, such as the URI or a cookiehash $…
By response timethe server with the lowest average response timeleast_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”.

Section sources

the section is written from these pages

Caching and compression

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.

nginxnginx.conf: response cache
http {    proxy_cache_path /var/cache/nginx/app        levels=1:2        keys_zone=app_cache:10m        inactive=60m        max_size=2g;     server {        listen 80;         location / {            proxy_pass         http://app;            proxy_cache        app_cache;            proxy_cache_valid 200 302 10m;            proxy_cache_valid 404      1m;        }    }}

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 parameterWhat it sets
paththe directory on disk where cache files are stored
keys_zonethe zone name and its memory for keys, for example app_cache:10m
inactiveremove an entry not accessed for this long; the default is 10 minutes
max_sizethe limit on the cache size on disk
levelssubdirectories 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.

ValueWhat happened
HITthe response was served from the cache; the application was not called
MISSthere was no entry in the cache; the response came from the application
EXPIREDthe cache entry had expired; nginx refreshed it from the application
BYPASSa proxy_cache_bypass condition sent the request past the cache
STALEa stale copy was served because of proxy_cache_use_stale
UPDATINGa copy was served while a new one is being fetched in the background
REVALIDATEDIf-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.

Section sources

the section is written from these pages

HTTPS and TLS

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.

nginxnginx.conf: a minimal HTTPS server
server {    listen 443 ssl;    listen [::]:443 ssl;    server_name example.com;     ssl_certificate     /etc/nginx/ssl/example.com.pem;    ssl_certificate_key /etc/nginx/ssl/example.com.key;     ssl_protocols TLSv1.2 TLSv1.3;     location / {        return 200 "ok";    }}

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).

nginxnginx.conf: session resumption
http {    ssl_session_cache   shared:SSL:10m;    ssl_session_timeout 1d;    ssl_session_tickets on;}
DirectiveDefaultWhat it does
ssl_protocolsTLSv1.2 TLSv1.3 (since 1.27.3)which TLS versions to accept
ssl_session_cachenonesession cache: shared:SSL:10m is 10 MB shared by all worker processes
ssl_session_timeout5mhow long a client can reuse session parameters
ssl_session_ticketsonresumption 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).

nginxnginx.conf: HTTP/2
server {    listen 443 ssl;    http2 on;     ssl_certificate     /etc/nginx/ssl/example.com.pem;    ssl_certificate_key /etc/nginx/ssl/example.com.key;}

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.

nginxnginx.conf: HTTP/3 alongside HTTPS
server {    listen 443 quic reuseport;    listen 443 ssl;     http2 on;     ssl_certificate     /etc/nginx/ssl/example.com.pem;    ssl_certificate_key /etc/nginx/ssl/example.com.key;     add_header Alt-Svc 'h3=":443"; ma=86400';}

A Let’s Encrypt certificate inside nginx

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.

nginxnginx.conf: HSTS
add_header Strict-Transport-Security    "max-age=31536000; includeSubDomains" always;

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

Section sources

the section is written from these pages

Security and request limiting

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
http {    limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;     server {        location / {            limit_req zone=perip burst=20 nodelay;        }    }}

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.

ParameterWhat it doesDefault
rate=10r/sthe average rate in the zonenone; always required
burst=20the size of the burst queue0; all excess is rejected
nodelaya burst without delays inside burstpermitted requests are delayed
delay=5the first 5 excess requests are not delayed, later ones are0; all are delayed
limit_req_status 429the response code for rejected requests503

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
http {    limit_conn_zone $binary_remote_addr zone=perip:10m;     server {        location /files/ {            limit_conn perip 4;        }    }}

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:

nginxnginx.conf: trusted networks only
location /admin/ {    allow 192.0.2.0/24;    allow 2001:db8::/32;    deny  all;}

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

BadWhy it is dangerousGood
location /img { alias /data/; }/img../etc/passwd reads files outside the site rootlocation /img/ { alias /data/; } with a trailing slash on the location
proxy_pass for everything without limitsone client ties up the application with requests and connectionslimit_req and limit_conn in front of the proxy
auth_basic without HTTPSthe password travels in clear textlisten 443 ssl first, then the password
no client_max_body_size at the server levelthe default of 1m breaks uploads, and the application may have no limit of its ownan explicit limit: a general one and a separate one for uploads
autoindex on; for the whole sitevisitors see directory listingsautoindex 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).

Section sources

the section is written from these pages

Common errors and diagnostics

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

  1. nginx -t: configuration syntax, and opening the files it refers to;
  2. systemctl status nginx: whether the service is running, if it is started by systemd;
  3. error.log: startup and proxying errors, with the text of the system error;
  4. access.log with $status and $upstream_status: what the client received and what the upstream server returned;
  5. 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:

bashon the server
nginx -tsudo journalctl -u nginx -n 20sudo tail -n 20 /var/log/nginx/error.log

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:

textexample error.log entry
connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.7, server: example.com, request: "GET /api HTTP/1.1", upstream: "http://127.0.0.1:8000/api", host: "example.com"

“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.

bashon the nginx host
curl -v http://127.0.0.1:8000/healthgrep -n proxy_pass /etc/nginx/conf.d/app.conf

504 Gateway Time-out

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.

nginxnginx.conf: limit for uploads
location /upload/ {    client_max_body_size 20m;    proxy_pass http://app;}

403 Forbidden

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
sudo ls -l /var/www/example.com/index.htmlnginx -T 2>/dev/null | grep -n 'root\|index\|user '

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.

bashfind the file and apply the change
nginx -T 2>/dev/null | grep -n listennginx -t && nginx -s reload

Access log for a proxy

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.

nginxnginx.conf: a custom log format
log_format upstream '$remote_addr msec=$msec '    '"$request" $status us=$upstream_status '    'ua=$upstream_addr urt=$upstream_response_time'; server {    access_log /var/log/nginx/app.access.log upstream;}
textexample access.log entry
203.0.113.7 msec=1793960641 "GET /api HTTP/1.1" 502 us=502 ua=127.0.0.1:8000 urt=0.001

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.

nginxnginx.conf: debug log for selected addresses
error_log /var/log/nginx/error.log; events {    debug_connection 192.0.2.0/24;}

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.

Section sources

the section is written from these pages

Versions and what’s new

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.
BranchStatusLatest release
1.31mainline, new features1.31.8 — 21 October 2026
1.30stable, current1.30.6 — 14 October 2026
1.28legacy, 1.30 fixes are not backported1.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

IdentifierWhat is affectedFixed in
CVE-2026-15176Buffer overflow when rewrite changes the URI in a location with alias1.30.6
CVE-2026-93479Buffer overflow when evaluating expressions with variables1.30.6
CVE-2026-95101HTTP/3: part of an unknown frame ends up in the request body1.30.6
CVE-2026-97629TLS session spoofing during session ticket rotation1.30.6
CVE-2026-97205Use-after-free with asynchronous I/O and SSI include1.30.6
CVE-2026-90439Buffer overflow in HTTP/3 with OpenSSL 3.5.01.30.5
CVE-2026-42533Buffer overflow in map with regular expressions1.30.4
CVE-2026-42055Buffer overflow in HTTP/2 and gRPC proxying1.30.3
CVE-2026-9256Buffer overflow in rewrite1.30.2
CVE-2026-42926HTTP/2: request data injection through proxy_set_body1.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.

bashupgrading the binary without downtime
sudo cp /usr/sbin/nginx /usr/sbin/nginx.oldsudo cp ~/nginx-1.30.6/nginx /usr/sbin/nginxsudo kill -USR2 $(cat /run/nginx.pid)sudo kill -WINCH $(cat /run/nginx.pid.oldbin)sudo kill -QUIT $(cat /run/nginx.pid.oldbin)

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

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.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. 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. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 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

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Nginx” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61