A practical guide to the web server & reverse proxy, centered on nginx.conf
π Nginx Complete Guide
Covers Nginx at a working level, centered on nginx.conf: contexts and the request processing order, server_name and location matching rules, the root/alias and proxy_pass slash traps, the add_header inheritance problem, map variables, reverse proxy keepalive and WebSocket, TLS, rate limiting and security headers, the proxy cache, debugging, and a full production template.
Covers Nginx at a working level, centered on nginx.conf: contexts and the request processing order, server_name and location matching rules, the root/alias and proxy_pass slash traps, the add_header inheritance problem, map variables, reverse proxy keepalive and WebSocket, TLS, rate limiting and security headers, the proxy cache, debugging, and a full production template. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Infrastructure / operations
Rather than memorizing install commands, understand the order in which traffic, runtime, observability, and incident response connect.
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Nginx.
Learning flow
Rendering diagramβ¦
Architecture view
Rendering diagramβ¦
Installation
When you first open Nginx, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Production servers usually install it directly with the package manager and manage it with systemd, while local tests and container environments often bring it up quickly with the official Docker image. After changing the configuration, check for syntax errors with nginx -t first and only then reload, to avoid an incident where a typo takes the whole service down.
BASH
# Ubuntu/Debiansudo apt update && sudo apt install -y nginxsudo systemctl enable --now nginx# macOSbrew install nginx# Dockerdocker run -d -p 80:80 -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro nginxnginx -v # check the versionnginx -t # check the configuration syntaxsudo nginx -s reload # reapply the configuration with no downtime
Configuration structure
Here you look at Configuration structure alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
An Nginx configuration typically has the top-level `nginx.conf` load `sites-available/*` (available configurations) through `sites-enabled/*` (configurations enabled by symbolic link). One `server` block is responsible for one domain/port.
The static file root path and the file lookup order
nginx.conf context structure
Here you look at nginx.conf context structure alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
nginx.conf is made up of hierarchical contexts. Directives in a parent context are inherited downward, and writing the same directive again in a child overrides it within that scope only. Without knowing this inheritance rule, it is easy to run into the "I definitely set it, but it does not apply in one particular location" problem.
/etc/nginx/nginx.confNGINX
user nginx;worker_processes auto;error_log /var/log/nginx/error.log warn;pid /run/nginx.pid;events { worker_connections 1024;}http { include /etc/nginx/mime.types; # extension β Content-Type mapping table default_type application/octet-stream; # default for extensions not in the mapping log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; gzip on; # Per-domain configuration is managed in separate files include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;}
Context
Role
Typical directives
main (top level)
Global settings such as worker processes and logs
user, worker_processes, error_log, pid
events
How connections are handled
worker_connections, use
http
Global web server settings β the parent of every server block
include mime.types, default_type, sendfile, gzip, log_format
server
A virtual host responsible for one domain/port
listen, server_name, root, index, ssl_certificate
location
Detailed handling rules per URL path
try_files, proxy_pass, alias, return, rewrite
The order in which one request passes through nginx.conf
Here you look at The order in which one request passes through nginx.conf alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The most important instinct when reading nginx.conf is "in what order does a single request choose which block?". Nginx β narrows the candidate server blocks by the IP:port the request arrived on, β‘ compares the Host header against server_name to choose one server, β’ compares the URI against the location rules to choose one location, and β£ runs the directives inside that location (rewrite β access control β try_files/proxy_pass) in a fixed order of phases. The key point is that it is not a script executed top to bottom in the order written in the configuration file.
Rendering diagramβ¦
Phase
Typical directives
What trips people up in practice
server selection
listen, server_name
If the Host matches nothing, default_server (or the first server if there is none) answers.
location selection
location
Decided by the priority of the matching rules, not the order in the file (order matters only among regexes).
rewrite
rewrite, return, set, if
return ends the response immediately, so every directive after it is ignored.
access
allow/deny, limit_req, auth_basic
allow/deny is decided by the first match from the top.
content
try_files, proxy_pass, root/alias
Only one content handler runs per location.
filter
gzip, add_header
By default add_header is attached only to 2xx/3xx responses (extend with always).
Configuration file layout & include strategy
Here you look at Configuration file layout & include strategy alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
How the configuration files are split depends on the distribution and the installation method. The Debian/Ubuntu packages use the sites-available / sites-enabled structure, while the official nginx.org packages and the official Docker image use the conf.d/*.conf structure. Mixing the two loads the same server_name twice, producing a "conflicting server name" warning and the wrong block answering, so standardize on one as a team. Collect settings repeated across several server blocks in snippets/ and reuse them with include.
Recommended /etc/nginx directory structureTEXT
/etc/nginx/
βββ nginx.conf # only the global main / events / http settings
βββ mime.types # extension β Content-Type mapping (do not edit)
βββ conf.d/
β βββ 00-upstreams.conf # collection of upstream blocks (loaded in filename order)
β βββ 10-maps.conf # map variable definitions
β βββ api.example.com.conf
β βββ www.example.com.conf
βββ snippets/
βββ proxy-headers.conf # bundle of proxy_set_header directives
βββ security-headers.conf
βββ ssl-params.conf # common TLS settings
server { listen 443 ssl; http2 on; server_name api.example.com; include snippets/ssl-params.conf; include snippets/security-headers.conf; location / { include snippets/proxy-headers.conf; proxy_pass http://api_backend; }}
Commands for checking the configurationBASH
sudo nginx -t # check syntax + file pathssudo nginx -T # print "the full configuration actually loaded", with every include expandedsudo nginx -T | grep -n "server_name" # find duplicate server_name entriesnginx -V # check compile options and included modules (http_v2, stream, and so on)
The main & events contexts
Here you look at The main & events contexts alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The top-level (main) and events contexts determine the number of worker processes and the concurrent connection limit. The theoretical maximum number of concurrent connections is worker_processes Γ worker_connections, and since a reverse proxy uses one more upstream connection per client connection, the number of clients it can really serve is about half that. When raising the connection count, raise the OS file descriptor limit (worker_rlimit_nofile) along with it to avoid "Too many open files" errors.
nginx.conf (main / events)NGINX
user nginx;worker_processes auto; # create as many workers as CPU coresworker_rlimit_nofile 65535; # limit on files (including sockets) a worker can openpid /run/nginx.pid;error_log /var/log/nginx/error.log warn;# Dynamic modules are loaded in the main context# load_module modules/ngx_http_geoip2_module.so;events { worker_connections 8192; # maximum concurrent connections per worker multi_accept on; # accept all pending connections at once # use epoll; # chosen automatically on Linux, so usually omitted}
Directive
Default
Recommended starting point
Notes
worker_processes
1
auto
The more CPU-bound work (TLS, gzip), the bigger the gain from matching the core count
worker_connections
512
4096 to 16384
Must be smaller than worker_rlimit_nofile
worker_rlimit_nofile
OS limit
At least worker_connections Γ 2
Must also match LimitNOFILE in systemd
error_log level
error
warn (info/debug when analyzing an incident)
debug works only in builds made --with-debug
The http context β designing global defaults
Here you look at The http context β designing global defaults alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The http block is the parent of every server block, so this is where to put "safe defaults applied to all sites alike". In particular, the defaults for client_max_body_size (1m by default) and the various timeouts often do not fit real requirements, and they are the cause of 413 errors on file uploads and 504 errors on slow APIs. Writing logs in JSON format lets collectors such as Loki and Elasticsearch search and aggregate by field.
nginx.conf (http)NGINX
http { include /etc/nginx/mime.types; default_type application/octet-stream; charset utf-8; server_tokens off; # hide the version from error pages and the Server header # ββ Transfer optimization βββββββββββββββββββ sendfile on; # copy files straight to the socket in the kernel tcp_nopush on; # with sendfile: headers + data in one packet tcp_nodelay on; # remove small-packet delay on keepalive connections # ββ Timeouts & request size βββββββββββββββββ keepalive_timeout 65s; client_header_timeout 15s; client_body_timeout 30s; send_timeout 30s; client_max_body_size 20m; # default 1m β 413 Request Entity Too Large when exceeded # ββ JSON access log βββββββββββββββββββββββββ log_format json escape=json '{' '"time":"$time_iso8601",' '"request_id":"$request_id",' '"remote_addr":"$remote_addr",' '"host":"$host",' '"method":"$request_method",' '"uri":"$request_uri",' '"status":$status,' '"bytes":$body_bytes_sent,' '"request_time":$request_time,' '"upstream_addr":"$upstream_addr",' '"upstream_status":"$upstream_status",' '"upstream_response_time":"$upstream_response_time",' '"user_agent":"$http_user_agent"' '}'; access_log /var/log/nginx/access.log json buffer=32k flush=5s; # ββ Compression βββββββββββββββββββββββββββββ gzip on; gzip_comp_level 5; gzip_min_length 1024; gzip_proxied any; # compress proxied responses too gzip_vary on; # Vary: Accept-Encoding (separates CDN caches) gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml; include /etc/nginx/conf.d/*.conf;}
Server block selection rules (listen & server_name)
Here you look at Server block selection rules (listen & server_name) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Nginx first narrows the candidates by the IP:port of the listen directive, then compares the Host header against server_name. The matching priority is β the exact name β β‘ the longest wildcard starting with * β β’ the longest wildcard ending with * β β£ the first regex that matches in configuration order. If no name matches, the default_server for that port answers, and if you do not declare one, "the first server block loaded" becomes the default, exposing your real service to scanner requests that come in directly by IP.
# Unregistered Hosts (direct IP access, scanners) get the connection dropped with no responseserver { listen 80 default_server; listen 443 ssl default_server; server_name _; ssl_reject_handshake on; # 1.19.4+: refuse the TLS handshake itself, with no certificate return 444; # nginx-specific code: close the connection without a response}
# Canonicalize http β https and www β apex in one hopserver { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri;}server { listen 443 ssl; http2 on; server_name www.example.com; include snippets/ssl-params.conf; return 301 https://example.com$request_uri;}server { listen 443 ssl; http2 on; server_name example.com; include snippets/ssl-params.conf; root /var/www/example;}
server_name matching examplesNGINX
server_name example.com; # β exact nameserver_name *.example.com; # β‘ leading wildcard (a.example.com, a.b.example.com)server_name mail.*; # β’ trailing wildcardserver_name ~^(?<tenant>[a-z0-9-]+)\.saas\.com$; # β£ regex + named capture# Regex captures can be used as variables in later directives# root /var/www/tenants/$tenant;
Mastering the location matching rules
Here you look at Mastering the location matching rules alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Locations are not checked in the order written in the file. Nginx β settles immediately if there is an = exact match, β‘ remembers the longest of the prefix string locations and, if that one is ^~, skips the regex check and settles on it. β’ Otherwise it checks the regex locations (~ case-sensitive, ~* case-insensitive) in file order and uses the first that matches, and β£ uses the remembered longest prefix location only when no regex matches. In other words, the phenomenon of "I wrote a more specific prefix location but a regex location intercepts it" is the rules working as designed.
# SPA: look up file β directory β index.html in that orderlocation / { try_files $uri $uri/ /index.html;}# Hand off to the backend when there is no static file (Rails/Django/Next.js and so on)location / { try_files $uri @app;}location @app { include snippets/proxy-headers.conf; proxy_pass http://app_backend;}
Syntax
Meaning
Example: a request for /images/logo.png
location = /images/logo.png
Exact match β checked first, ends matching immediately
This location is chosen
location ^~ /images/
Prefix match + skips the regex check
Chosen without looking at regexes if this is the longest prefix
location ~* \.(png|jpg)$
Regex (case-insensitive), in file order
Without ^~, this takes priority over the /images/ prefix
location /images/
Plain prefix match (longest match)
Chosen only when no regex matches
location /
The final fallback for every request
When nothing else matches
location @fallback
A named location β cannot be matched by external requests
The internal jump target of try_files and error_page
root vs alias, and the proxy_pass slash trap
Here you look at root vs alias, and the proxy_pass slash trap alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
These are the two traps that cause the most 404s and security incidents in nginx.conf. root finds the file as "the root path + the full URI", while alias "replaces the part matched by the location with the alias path". proxy_pass is similar: if a URI (even a single slash) follows the address, the part matched by the location is replaced with that URI, and if not, the original URI is passed through unchanged.
A dangerous alias (off-by-slash vulnerability)NGINX
# β No trailing slash on the location, but one on the aliaslocation /static { alias /var/www/static/;}# GET /static../app/.env β /var/www/static/../app/.env (parent directory exposed!)# β Always match the trailing slash on the location and the aliaslocation /static/ { alias /var/www/static/;}
Regex location + alias / proxy_passNGINX
# To use alias in a regex location you must assemble the path yourself from captureslocation ~ ^/download/(.+\.pdf)$ { alias /data/files/$1;}# A URI cannot be attached to proxy_pass inside a regex location (nginx -t error)# To change the path, modify the URI first with rewrite ... breaklocation ~ ^/api/v1/(.*)$ { rewrite ^/api/v1/(.*)$ /$1 break; proxy_pass http://api_backend;}
Here you look at Directive inheritance traps (add_header, proxy_set_header) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Directives in a parent context are inherited downward, but for "array-type" directives that can be written several times, such as add_header and proxy_set_header, having even one of the same directive in a child block makes all the parent values disappear (they are not merged). The classic incident is putting security headers on the server, adding just one Cache-Control to a particular location, and losing every security header in that location.
β A configuration that loses the security headersNGINX
server { add_header X-Frame-Options "DENY" always; add_header X-Content-Type-Options "nosniff" always; location /assets/ { add_header Cache-Control "public, max-age=31536000, immutable"; # β responses from this location have no X-Frame-Options or X-Content-Type-Options! }}
β Reapply explicitly with a snippet includeNGINX
# snippets/security-headers.confadd_header X-Frame-Options "DENY" always;add_header X-Content-Type-Options "nosniff" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;# conf.d/example.com.confserver { include snippets/security-headers.conf; location /assets/ { include snippets/security-headers.conf; # include again add_header Cache-Control "public, max-age=31536000, immutable"; }}
Directive
How it inherits
Caution
add_header
Any in the child means all parent ones are ignored
Without always, not attached to 4xx/5xx responses
proxy_set_header
Any in the child means all parent ones are ignored
Falls back to the defaults (Host $proxy_host, Connection close)
root, index, client_max_body_size
Normal inheritance β overridden in the child
The value can be changed per location
rewrite, return
Not inherited (works only in its own block)
A server-level rewrite runs before location selection
Variables, map, and how to avoid if
Here you look at Variables, map, and how to avoid if alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Nginx variables are evaluated per request ($host, $uri, $request_uri, $remote_addr, $http_HEADER, $cookie_NAME, $arg_PARAM, and so on), and a map block can derive one variable from another. An if inside a location works by creating a separate location internally, and it is notorious for behaving unexpectedly when mixed with directives other than return and rewrite ("If is Evil"). Turn conditional branching into a map wherever you can, and use if only for return.
server { access_log /var/log/nginx/access.log json if=$loggable; location / { # Only during maintenance, uncomment the line below and reload β internal IPs pass # if ($maintenance_block) { return 503; } add_header Cache-Control $cache_control always; try_files $uri $uri/ /index.html; }}
Reverse proxy & load balancing
Here you look at Reverse proxy & load balancing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
With several backend instances behind Nginx, an `upstream` block can distribute requests among them. The default is round robin; use `ip_hash` if you need session stickiness.
Rendering diagramβ¦
reverse-proxy.confNGINX
upstream backend { server 127.0.0.1:3000; server 127.0.0.1:3001; server 127.0.0.1:3002; # ip_hash; # when you want to pin the same client to the same server}server { listen 80; server_name api.example.com; location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }}
Here you look at Advanced reverse proxying β keepalive, timeouts, WebSocket alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A basic proxy_pass alone falls short on performance and stability under production traffic. By default Nginx opens a new TCP connection to the upstream over HTTP/1.0 for every request, so you need to turn on upstream keepalive to reuse connections (which requires proxy_http_version 1.1 and an empty Connection header). You also need to set the conditions for moving on to another server when a backend fails (proxy_next_upstream) and the timeouts to suit the nature of the API, or you cannot contain a surge of 502/504s.
conf.d/00-upstreams.confNGINX
upstream api_backend { least_conn; # to the server with the fewest active connections server 10.0.1.11:8080 max_fails=3 fail_timeout=30s; server 10.0.1.12:8080 max_fails=3 fail_timeout=30s; server 10.0.1.13:8080 backup; # used only when all the others are down keepalive 64; # idle connections to keep per worker keepalive_timeout 60s;}
conf.d/api.example.com.conf (location)NGINX
location /api/ { proxy_pass http://api_backend; proxy_http_version 1.1; proxy_set_header Connection ""; # required for keepalive reuse proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 3s; # connection setup limit β keep it short proxy_send_timeout 30s; proxy_read_timeout 30s; # wait for the response (default 60s) β 504 when exceeded # On connection failure, timeout, or 502/503, retry on the next server (idempotent requests such as GET only) proxy_next_upstream error timeout http_502 http_503; proxy_next_upstream_tries 2;}# WebSocket / SSElocation /ws/ { proxy_pass http://api_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; # the map from 10-maps.conf proxy_set_header Host $host; proxy_read_timeout 1h; # so idle connections are not dropped}location /events/ { # Server-Sent Events proxy_pass http://api_backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; # flush events through immediately proxy_cache off; proxy_read_timeout 1h;}
With an LB/CDN in front β restoring the real client IPNGINX
# ngx_http_realip_module: take the IP only from headers sent by trusted proxiesset_real_ip_from 10.0.0.0/8; # internal LB rangeset_real_ip_from 173.245.48.0/20; # (example) CDN range β manage from the official listreal_ip_header X-Forwarded-For;real_ip_recursive on;# From here on $remote_addr is the real client IP, reflected in logs, limit_req, and allow/deny
Symptom
Meaning
Settings to check first
502 Bad Gateway
Could not connect to the upstream, or the response was broken
The upstream address/port, the backend process state, connect() failed in error.log
504 Gateway Timeout
The upstream did not respond within the time limit
proxy_read_timeout, slow queries on the backend
499 (in logs only)
The client closed the connection before the response
Whether the client/LB timeout is shorter than that of Nginx
upstream sent too big header
The response headers (cookies and so on) are larger than the buffer
proxy_buffer_size 16k, proxy_buffers 8 16k
Serving static files
Here you look at Serving static files alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Nginx serves static files far faster than an application server. Setting cache headers together with gzip compression greatly reduces the cost of delivering frontend assets.
Serving a default image when the file is missing (try_files)
Here you look at Serving a default image when the file is missing (try_files) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
For paths where the file may not exist yet, such as product images or profile photos, it is better to show a default image than a broken one. try_files expresses "the requested file if it exists, otherwise the default image" in one line.
The last argument of try_files is not a file but an internal redirect target. The path changes only inside the server, so the address in the browser stays the requested /images/product123.png and the response code is 200.
The configurations and responses below were run and checked on Nginx 1.30.
GET /images/product123.png
ββ file exists β returns product123.png (200)
ββ file missing β returns default.png (200, the address stays the same)
GET /images/not-found.png (when default.png is missing too)
ββ 500 Internal Server Error
error.log: rewrite or internal redirection cycle while internally redirecting to "/images/default.png"
2. Recommended for productionNGINX
server { listen 80; server_name example.com; root /usr/share/nginx/html; # Real images: cache for longer location /images/ { try_files $uri /images/default.png; expires 1h; } # Default image: handled separately with a short cache, and a plain 404 if even this file is missing location = /images/default.png { try_files /images/default.png =404; expires 10m; }}
3. When the URL path and the directory differ (alias)NGINX
server { listen 80; server_name example.com; # /images/product123.png β /data/uploads/product123.png location /images/ { alias /data/uploads/; try_files $uri @default_image; } # A named location reached only when the file is missing location @default_image { root /data/default; try_files /default.png =404; expires 10m; }}
4. Applying it to image extensions onlyNGINX
# Configuration 1 returns the default image even for non-image requests such as /images/readme.txt.# To replace only image extensions and leave the rest as 404, use a regex location.location ~* ^/images/.+\.(png|jpe?g|gif|webp|svg)$ { try_files $uri /images/default.png;}
5. Keep the 404 status and replace only the bodyNGINX
# The page shows the default image, but the response code stays 404.# Use this when logs and monitoring have to tell "requests for missing images" apart.location /images/ { error_page 404 /images/default.png;}
Configuration
When the image is missing
When the default image is missing too
When to use
1. Basic try_files
200 + default image
500 (internal redirect cycle)
The simplest setup
2. Dedicated location for the default image
200 + default image (short cache)
404
Production (recommended)
3. alias + named location
200 + default image
404
Files on a separate volume or in another directory
5. error_page
404 + default image
404
When missing files have to be tracked by status code
Default image configuration β differences between Nginx 1.2x and 1.30
Here you look at Default image configuration β differences between Nginx 1.2x and 1.30 alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Production servers often still run older versions such as 1.20, 1.22, or 1.24. The conclusion first: the default image configurations above work on older versions unchanged.try_files, named locations, error_page, and expires have all existed for a long time.
The same configuration file was run on Nginx 1.20.2, 1.28.3, and 1.30.5, comparing the status code, Content-Type, Cache-Control, and body, and the results were identical. They were the same on 1.2.9 from 2012 as well. What differs is not the configuration itself but two things around it.
AVIF images on Nginx 1.20 β add the MIME typeNGINX
http { include mime.types; # mime.types in 1.20 has no avif entry. Add it in the http block. # (a types block inside server or location replaces the whole of mime.types, so it must go in the http block) types { image/avif avif; } default_type application/octet-stream;}
server { add_header X-Content-Type-Options nosniff; location /images/ { try_files $uri /images/default.png; # A single add_header in a location stops the server-level add_header from being inherited. # On older versions, the headers you need have to be repeated in the location. add_header Cache-Control "public, max-age=3600"; add_header X-Content-Type-Options nosniff; }}
Nginx 1.30 β merge inherited headersNGINX
server { add_header X-Content-Type-Options nosniff; add_header_inherit merge; # 1.29.3 and later: merge the parent block's headers instead of dropping them location /images/ { try_files $uri /images/default.png; add_header Cache-Control "public, max-age=3600"; # Response: both Cache-Control and X-Content-Type-Options are sent }}
Check the version of your serverBASH
nginx -v# nginx version: nginx/1.24.0
Item
1.20 ~ 1.28
1.30
Effect
try_files $uri /default-image
Works
Works
No difference
Dedicated location for the default image (= /images/default.png)
Works
Works
No difference
alias + try_files + named location
Works
Works
No difference
error_page 404 /default-image
Works
Works
No difference
When the default image is missing
500 (cycle detected)
500 (cycle detected)
No difference
MIME type for AVIF (mime.types)
Missing in 1.20.2, present from 1.24.0
Present
On 1.20, .avif is sent as application/octet-stream, so the image is downloaded instead of displayed.
On older versions, an add_header in a location drops every add_header from the server block.
Fixing files that download instead of displaying
Here you look at Fixing files that download instead of displaying alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Whether the browser renders a response on screen or downloads it is decided solely by the `Content-Type` response header. Nginx looks up the extension of the file it serves in `mime.types` to set the Content-Type, and if it is not listed, falls back to `default_type` (default `application/octet-stream` β "unknown binary file"). When a request comes in with a custom extension other than `.html`, such as `index.test`, in a setup that internally stitches in the real html, this fallback is what makes the download dialog appear in most cases.
diagnose.shBASH
# Start by checking directly which Content-Type actually comes back (check http and https the same way)curl -I http://example.com/index.testcurl -I https://example.com/index.test# β if it is Content-Type: application/octet-stream, apply the fixes below
The most common fix β route the static file internally to .htmlNGINX
location = /index.test { default_type text/html; # responses from this location are always fixed to text/html try_files /index.html =404; # serve the real html file internally (the URL stays /index.test; no redirect is exposed to the client)}
Mapping several .test files to their respective .html filesNGINX
location ~ \.test$ { rewrite ^(.*)\.test$ $1.html last; # last changes the URI to .html and restarts location matching from the beginning β # it is then served normally as .html from the general location (/), so mime.types correctly picks text/html.}
When the backend behind proxy_pass is the causeNGINX
location = /index.test { proxy_pass http://backend; proxy_hide_header Content-Type; # remove the wrong/missing Content-Type sent by the backend add_header Content-Type "text/html; charset=utf-8" always;}
Diagnosis (curl -I result)
Cause
Fix
Content-Type: application/octet-stream
`.test` is not in mime.types and falls back to default_type
Pass it internally to the real .html with try_files/rewrite, or force default_type in the location
A Content-Disposition: attachment header is present
A header forcing download is set in a parent (server/http) context
Remove that add_header or limit it to the locations that need it
Content-Type is missing or empty
The backend behind proxy_pass does not send the header
Override it in nginx with proxy_hide_header + add_header
HTTPS (TLS) setup
Here you look at HTTPS (TLS) setup alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
With certbot from Let's Encrypt, free certificate issuance and automatic renewal hook straight into the Nginx configuration. Because certbot reads the Nginx configuration file itself and adds the SSL-related directives automatically, the switch to HTTPS is done with a single command, with no need to line up certificate paths and protocol versions by hand. If you have several sites, split the common TLS settings into snippets/ssl-params.conf so every server block has the same security level. From Nginx 1.25.1 on, use the separate directive http2 on; instead of listen 443 ssl http2.
BASH
sudo apt install -y certbot python3-certbot-nginxsudo certbot --nginx -d example.com -d www.example.com# The 80 β 443 redirect and certificate settings are then added automaticallysudo certbot renew --dry-run # test automatic renewal
snippets/ssl-params.confNGINX
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;ssl_protocols TLSv1.2 TLSv1.3; # TLS 1.0/1.1 disabledssl_prefer_server_ciphers off; # in the TLS 1.3 era, respect the client choicessl_session_cache shared:SSL:10m; # about 40,000 sessions β skips the handshake on reconnectssl_session_timeout 1d;ssl_session_tickets off;
snippets/hsts.confNGINX
# HSTS: browsers connect only over https for the next year (confirm https on every subdomain before applying!)# It is an add_header, so include this file too whenever you add an add_header to a locationadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Full example serving http + https togetherNGINX
# Port 80 β if needed, the same locations can be placed here and served as-isserver { listen 80; server_name example.com www.example.com; root /var/www/myapp; location = /index.test { default_type text/html; try_files /index.html =404; } location / { try_files $uri $uri/ =404; }}# Port 443 β even with TLS, the same locations as above are used unchangedserver { listen 443 ssl; http2 on; server_name example.com www.example.com; root /var/www/myapp; include snippets/ssl-params.conf; include snippets/hsts.conf; location = /index.test { default_type text/html; try_files /index.html =404; } location / { try_files $uri $uri/ =404; }}
Here you look at Security hardening β headers, access control, rate limiting alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
An Nginx exposed to the internet receives scanner traffic every day probing for paths such as .env, .git, and wp-admin. Putting hidden file blocking, IP restrictions on admin paths, request rate limiting (limit_req), concurrent connection limiting (limit_conn), and security response headers into your base template greatly reduces the attack surface without touching application code.
http context β defining the limit zonesNGINX
# Key: client IP (the binary form is memory efficient), 10MB β 160,000 IPslimit_req_zone $binary_remote_addr zone=api_rl:10m rate=10r/s;limit_req_zone $binary_remote_addr zone=login_rl:10m rate=5r/m;limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;limit_req_status 429; # the semantically correct 429 instead of the default 503limit_conn_status 429;
server context β applying themNGINX
server { include snippets/security-headers.conf; # Block hidden files (.env, .git ...) β but allow .well-known for ACME validation location ~ /\.(?!well-known/) { deny all; access_log off; log_not_found off; } location /api/ { limit_req zone=api_rl burst=20 nodelay; # allow bursts of up to 20, the excess gets 429 limit_conn conn_per_ip 20; include snippets/proxy-headers.conf; proxy_pass http://api_backend; } location = /api/auth/login { limit_req zone=login_rl burst=5; # defense against brute force include snippets/proxy-headers.conf; proxy_pass http://api_backend; } location /admin/ { allow 10.0.0.0/8; # the first matching rule from the top applies allow 203.0.113.10; deny all; include snippets/proxy-headers.conf; proxy_pass http://admin_backend; }}
snippets/security-headers.confNGINX
add_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "SAMEORIGIN" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;# CSP differs per service, so observe with Report-Only first and then enforce# add_header Content-Security-Policy-Report-Only "default-src 'self'" always;
limit_req option
Behavior
When to use it
rate=10r/s
Allows 10 per second at even intervals (100ms)
The average allowed rate
burst=20
Queues up to 20 excess requests
Absorbing normal traffic that bunches up briefly, as on page load
nodelay
Processes queued requests immediately, with no delay
APIs β when a fast response/fast rejection beats a delay
delay=8
The first 8 immediately, the rest of the burst delayed
A compromise between the two
Proxy cache (proxy_cache)
Here you look at Proxy cache (proxy_cache) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Caching API responses that are read often but change rarely (product lists, notices, settings) in Nginx cuts backend load and response time at once. With proxy_cache_use_stale on, it also acts as a "shock absorber" that keeps the service up by returning the last successful response even when the backend is down. On the other hand, if per-user responses (requests carrying Authorization or Cookie) are cached, personal data is exposed to other users, so they must be excluded from caching.
http contextNGINX
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:50m # key metadata (1MB β 8,000 keys) max_size=2g inactive=30m # deleted after 30 minutes with no requests use_temp_path=off;
Applying it in a locationNGINX
location /api/catalog/ { proxy_cache api_cache; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_valid 200 301 5m; proxy_cache_valid 404 1m; # While the backend is failing or being refreshed, answer even from a stale cache proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; proxy_cache_background_update on; proxy_cache_lock on; # send only 1 of the concurrent misses for a key to the backend # Personalized requests bypass the cache + are not stored proxy_cache_bypass $http_authorization $cookie_session; proxy_no_cache $http_authorization $cookie_session; add_header X-Cache-Status $upstream_cache_status always; # HIT / MISS / STALE ... include snippets/proxy-headers.conf; proxy_pass http://api_backend;}
Performance tuning
Here you look at Performance tuning alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
As traffic grows, the defaults alone stop being enough. Tune in the order "measure β change one thing β measure again"; the items below are starting points with proven effect in most services. If you serve many static files, cut file metadata lookups with open_file_cache, and if proxying is the main role, upstream keepalive and buffer sizes make the biggest difference.
http context β tuning blockNGINX
open_file_cache max=10000 inactive=30s;open_file_cache_valid 60s;open_file_cache_min_uses 2;open_file_cache_errors on;proxy_buffer_size 16k; # for response headers (allows for large cookies/JWTs)proxy_buffers 8 16k;proxy_busy_buffers_size 32k;reset_timedout_connection on; # reclaim the memory of timed-out connections immediately
stub_status β observing connection stateNGINX
server { listen 127.0.0.1:8081; # never expose externally location = /nginx_status { stub_status; allow 127.0.0.1; deny all; }}# curl 127.0.0.1:8081/nginx_status# Active connections: 291# server accepts handled requests# 16630948 16630948 31070465# Reading: 6 Writing: 179 Waiting: 106# β collect with nginx-prometheus-exporter and visualize in Grafana
Setting
Description
worker_processes auto;
Starts as many worker processes as CPU cores automatically
worker_connections 8192;
The maximum concurrent connections one worker can handle (together with worker_rlimit_nofile)
keepalive_timeout 65;
Reuses client connections to cut the cost of TLS handshakes
upstream keepalive 64;
Reuses backend connections β less proxy latency and fewer TIME_WAIT sockets
open_file_cache
Caches the fd and metadata of static files to reduce stat() calls
proxy_buffers / proxy_buffer_size
Handles large response headers and bodies in memory instead of on disk
limit_req_zone / limit_req
Defends against excessive traffic with per-IP rate limiting
Debugging the configuration & common errors
Here you look at Debugging the configuration & common errors alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Most configuration problems are solved by checking just two things: "which server and location were selected" and "what configuration was actually loaded". Always check changes with nginx -t and then apply them with reload (no downtime), and while debugging, adding a temporary header that shows the selected location in the response lets you judge by fact instead of guesswork.
Debugging routineBASH
sudo nginx -t && sudo systemctl reload nginx # reload only when the check passessudo nginx -T | less # the full configuration actually loaded# Vary the Host header to see which server block answerscurl -sI -H "Host: api.example.com" http://127.0.0.1/health# Test against a specific server IP including TLS SNI (verification before a DNS change)curl -sI --resolve example.com:443:203.0.113.5 https://example.com/sudo tail -f /var/log/nginx/error.log # most causes are logged here
Check the modules with nginx -V, check for a missing semicolon
conflicting server name ... ignored
The same server_name is defined in two places
Remove the duplicate using nginx -T | grep server_name
403 Forbidden
No index file in the directory, or insufficient file permissions
Check the index directive and that the nginx user has x permission all the way up the parent directories
404 (the file exists)
A wrong root/alias path combination
Check the path in "open() ... failed" in error.log
413 Request Entity Too Large
The upload size exceeds client_max_body_size
Raise the value in that server/location
502 + connect() failed (111: Connection refused)
The backend is not running, or the port does not match
Check the backend state and the upstream address
502 + (13: Permission denied) while connecting
SELinux is blocking network connections from Nginx
setsebool -P httpd_can_network_connect 1
504 upstream timed out
The backend response exceeded proxy_read_timeout
Split only the slow endpoints into their own location and adjust the timeout
rewrite or internal redirection cycle
try_files/rewrite jumps to itself forever
Use =404 as the last argument of try_files, check last/break on rewrite
Full production nginx.conf template
Here you look at Full production nginx.conf template alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
This template combines everything covered so far into one file structure. It follows the layout of global settings only in nginx.conf, per-site settings in conf.d/, and repeated settings in snippets/. Rather than copying it as-is, adjust the domains, upstream addresses, and limit values to your service and then verify with nginx -t.
As a web server for static files, a reverse proxy that forwards requests to application servers, a load balancer that spreads requests across servers, and the TLS termination point that handles HTTPS. One Nginx often plays several of these roles together.
Why do I get a 502 Bad Gateway error?
It means Nginx did not get a valid response from the application server behind it. Check that the application is running, that the address and port in proxy_pass are right, and that the application is listening on that address. The Nginx error log records whether the connection was refused or closed mid-response. A response that takes too long and times out shows up separately as a 504.
How do I apply a config change without interrupting service?
Check the syntax first with nginx -t, then run nginx -s reload. Reload starts new worker processes with the new configuration, and the old workers finish the requests in progress before exiting, so connections are not dropped. If there is a syntax error, the existing configuration stays in effect.