Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment Β· evaluation Β· observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification Β· coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
πŸ€– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
πŸ“± Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
βš™οΈ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
πŸ’Ύ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
πŸ§ͺ Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

Β 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
Β© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Infrastructure
  4. Nginx
A practical guide to the web server & reverse proxy, centered on nginx.conf

🌐 Nginx Complete Guide

Visitors

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.

  • Intermediate
  • Updated Oct 10, 2026
  • ~32 min read
  • 24 sections
  • 56 code examples
🌐
Designing nginx.confReverse proxy & load balancingServing static filesHTTPS (TLS) terminationRate limiting & security hardeningProxy cache

Contents

0 / 27
  1. How to use this guide
  2. Architecture diagrams
  3. Installation
  4. Configuration structure basics
  5. nginx.conf contexts
  6. Request processing order
  7. File layout & include
  8. main & events
  9. Global http defaults
  10. Server selection rules
  11. Location matching rules
  12. root/alias and proxy_pass traps
  13. Directive inheritance traps
  14. Variables & map
  15. Reverse proxy & load balancing
  16. Advanced proxying (keepalive, WS)
  17. Serving static files
  18. Missing image β†’ default image
  19. Version differences (1.2x Β· 1.30)
  20. Fixing files that download
  21. HTTPS (TLS) setup
  22. Security hardening & rate limiting
  23. Proxy cache
  24. Performance tuning
  25. Debugging & fixing errors
  26. Full production template
  27. Frequently asked questions
Contents 27 sections
  1. How to use this guide
  2. Architecture diagrams
  3. Installation
  4. Configuration structure basics
  5. nginx.conf contexts
  6. Request processing order
  7. File layout & include
  8. main & events
  9. Global http defaults
  10. Server selection rules
  11. Location matching rules
  12. root/alias and proxy_pass traps
  13. Directive inheritance traps
  14. Variables & map
  15. Reverse proxy & load balancing
  16. Advanced proxying (keepalive, WS)
  17. Serving static files
  18. Missing image β†’ default image
  19. Version differences (1.2x Β· 1.30)
  20. Fixing files that download
  21. HTTPS (TLS) setup
  22. Security hardening & rate limiting
  23. Proxy cache
  24. Performance tuning
  25. Debugging & fixing errors
  26. Full production template
  27. Frequently asked questions

How to use this guide

How to read it

Understanding Nginx as a real-world workflow

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.

Designing nginx.confReverse proxy & load balancingServing static filesHTTPS (TLS) terminationRate limiting & security hardeningProxy cache

Architecture diagrams

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/Debian
sudo apt update && sudo apt install -y nginx
sudo systemctl enable --now nginx

# macOS
brew install nginx

# Docker
docker run -d -p 80:80 -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro nginx

nginx -v            # check the version
nginx -t             # check the configuration syntax
sudo 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.
/etc/nginx/sites-available/myappNGINX
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/myapp;
        try_files $uri $uri/ /index.html;  # SPA routing
    }
}
DirectiveRole
listenPort and protocol (80, 443 ssl, and so on)
server_nameThe domain this server block answers for
locationHandling rules per URL path
root / try_filesThe static file root path and the file lookup order

Tip

After enabling it with `sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/`, always check the syntax with `nginx -t` and then `reload`.

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/*;
}
ContextRoleTypical directives
main (top level)Global settings such as worker processes and logsuser, worker_processes, error_log, pid
eventsHow connections are handledworker_connections, use
httpGlobal web server settings β€” the parent of every server blockinclude mime.types, default_type, sendfile, gzip, log_format
serverA virtual host responsible for one domain/portlisten, server_name, root, index, ssl_certificate
locationDetailed handling rules per URL pathtry_files, proxy_pass, alias, return, rewrite

Tip

  • With `default_type application/octet-stream;` in the http context, every extension missing from mime.types is treated as an "unknown binary file" and the browser shows a download dialog β€” the "Fixing files that download" section below deals with exactly this.
  • Location matching priority: checked in the order `location = /path` (exact match) β†’ `location ^~ /path` (prefix match, skips regex) β†’ `location ~/~* /regex` (regex) β†’ plain prefix strings (longest match). Make active use of `=` so the exact location you want is matched first.

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…
PhaseTypical directivesWhat trips people up in practice
server selectionlisten, server_nameIf the Host matches nothing, default_server (or the first server if there is none) answers.
location selectionlocationDecided by the priority of the matching rules, not the order in the file (order matters only among regexes).
rewriterewrite, return, set, ifreturn ends the response immediately, so every directive after it is ignored.
accessallow/deny, limit_req, auth_basicallow/deny is decided by the first match from the top.
contenttry_files, proxy_pass, root/aliasOnly one content handler runs per location.
filtergzip, add_headerBy 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
snippets/proxy-headers.confNGINX
proxy_http_version 1.1;
proxy_set_header Host              $host;
proxy_set_header X-Real-IP         $remote_addr;
proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Request-Id      $request_id;
conf.d/api.example.com.confNGINX
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 paths
sudo nginx -T          # print "the full configuration actually loaded", with every include expanded
sudo nginx -T | grep -n "server_name"   # find duplicate server_name entries
nginx -V               # check compile options and included modules (http_v2, stream, and so on)

Tip

  • If "I changed the configuration but it is not applied", look at the configuration actually loaded with nginx -T first. In most cases the edited file is not on an include path, or the symbolic link in sites-enabled is missing.
  • The official Docker image substitutes /etc/nginx/templates/*.template files with envsubst at container start and generates them into conf.d/. Use this to inject domains and upstream addresses as environment variables and you do not need to rebuild the image.
  • A wildcard in include loads files in alphabetical order of filename. For settings that must be defined first, such as upstream and map, pin the order with numeric prefixes like 00- and 10-.

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 cores
worker_rlimit_nofile 65535;       # limit on files (including sockets) a worker can open
pid /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
}
DirectiveDefaultRecommended starting pointNotes
worker_processes1autoThe more CPU-bound work (TLS, gzip), the bigger the gain from matching the core count
worker_connections5124096 to 16384Must be smaller than worker_rlimit_nofile
worker_rlimit_nofileOS limitAt least worker_connections Γ— 2Must also match LimitNOFILE in systemd
error_log levelerrorwarn (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;
}

Tip

  • Logging both $request_time (total processing time as seen from the client) and $upstream_response_time (backend response time) lets you tell from the logs alone whether a slow request is an Nginx/network problem or a backend problem.
  • Log $request_id and pass it to the backend with proxy_set_header X-Request-Id, and you can trace one request under the same id in the Nginx log and the application log.
  • text/html is always compressed even without listing it in gzip_types. Adding formats that are already compressed (jpg, png, woff2, zip) only wastes CPU.

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.
conf.d/00-default.conf β€” blocking unknown HostsNGINX
# Unregistered Hosts (direct IP access, scanners) get the connection dropped with no response
server {
    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
}
conf.d/www.example.com.conf β€” canonical redirectsNGINX
# Canonicalize http β†’ https and www β†’ apex in one hop
server {
    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 name
server_name *.example.com;               # β‘‘ leading wildcard (a.example.com, a.b.example.com)
server_name mail.*;                      # β‘’ trailing wildcard
server_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;

Tip

  • When redirecting with a 301, use return rather than rewrite. With no regex evaluation it is faster and the intent is clearer. $request_uri includes the query string, so parameters are not lost.
  • When using per-tenant subdomains as a SaaS does, a named capture in a regex server_name can extract the tenant for use in root or proxy_set_header.

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.
Location priority experimentNGINX
server {
    listen 8080;

    location = /           { return 200 "1. exact /\n"; }
    location ^~ /static/   { return 200 "2. ^~ /static/\n"; }
    location ~* \.(png|jpg|css|js)$ { return 200 "3. regex asset\n"; }
    location /api/         { return 200 "4. prefix /api/\n"; }
    location /             { return 200 "5. prefix / (fallback)\n"; }
}

# curl localhost:8080/                β†’ 1. exact /
# curl localhost:8080/static/app.js   β†’ 2. ^~ /static/    (takes priority over regex)
# curl localhost:8080/img/logo.png    β†’ 3. regex asset
# curl localhost:8080/api/logo.png    β†’ 3. regex asset    (the regex beats the /api/ prefix!)
# curl localhost:8080/api/users       β†’ 4. prefix /api/
# curl localhost:8080/about           β†’ 5. prefix / (fallback)
try_files & named locationsNGINX
# SPA: look up file β†’ directory β†’ index.html in that order
location / {
    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;
}
SyntaxMeaningExample: a request for /images/logo.png
location = /images/logo.pngExact match β€” checked first, ends matching immediatelyThis location is chosen
location ^~ /images/Prefix match + skips the regex checkChosen without looking at regexes if this is the longest prefix
location ~* \.(png|jpg)$Regex (case-insensitive), in file orderWithout ^~, 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 requestWhen nothing else matches
location @fallbackA named location β€” cannot be matched by external requestsThe internal jump target of try_files and error_page

Tip

  • To stop requests under /api/ from being intercepted by a static file regex location, declare it as location ^~ /api/. ^~ means "if this prefix is the longest match, do not look at regexes".
  • A location can be nested inside a location, but complex nesting such as a prefix location inside a regex location is hard to read. Most cases are solved with a flat structure that uses ^~ and = appropriately.
  • The last argument of try_files is not a "file" but an internal redirect target (a URI, an @name, or =code). Mistaking the last argument for a file can cause an infinite loop when there is no /index.html file, so get familiar with the form that ends in =404 as well.

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 alias
location /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 alias
location /static/ {
    alias /var/www/static/;
}
Regex location + alias / proxy_passNGINX
# To use alias in a regex location you must assemble the path yourself from captures
location ~ ^/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 ... break
location ~ ^/api/v1/(.*)$ {
    rewrite ^/api/v1/(.*)$ /$1 break;
    proxy_pass http://api_backend;
}
ConfigurationRequestFile actually looked up / URI passed on
location /static/ { root /var/www; }/static/app.js/var/www/static/app.js
location /static/ { alias /var/www/assets/; }/static/app.js/var/www/assets/app.js
location /api/ { proxy_pass http://be; }/api/usershttp://be/api/users (unchanged)
location /api/ { proxy_pass http://be/; }/api/usershttp://be/users (/api/ β†’ / replaced)
location /api/ { proxy_pass http://be/v2/; }/api/usershttp://be/v2/users

Tip

  • When the path structure is the same, root is safer and simpler than alias. Use alias only when the URL path and the disk path have to differ.
  • Using a variable in proxy_pass (e.g. proxy_pass http://$backend;) means no URI replacement happens, and a resolver directive becomes necessary when a domain name is used. The behavior changes, so be sure to test.

Directive inheritance traps (add_header, proxy_set_header)

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.conf
add_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.conf
server {
    include snippets/security-headers.conf;

    location /assets/ {
        include snippets/security-headers.conf;   # include again
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}
DirectiveHow it inheritsCaution
add_headerAny in the child means all parent ones are ignoredWithout always, not attached to 4xx/5xx responses
proxy_set_headerAny in the child means all parent ones are ignoredFalls back to the defaults (Host $proxy_host, Connection close)
root, index, client_max_body_sizeNormal inheritance β€” overridden in the childThe value can be changed per location
rewrite, returnNot inherited (works only in its own block)A server-level rewrite runs before location selection

Tip

For array-type directives, keep to the principle "put them only in the parent, or if you put any in a child, write all of them again", and handle that repetition with a snippet include β€” this causes the fewest mistakes.

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.
conf.d/10-maps.confNGINX
# WebSocket upgrade header
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

# Maintenance mode: internal IPs pass, everyone else gets 503
geo $maintenance_bypass {
    default      0;
    10.0.0.0/8   1;
    192.168.0.0/16 1;
}

map $maintenance_bypass $maintenance_block {
    1       0;
    default 1;
}

# Exclude bot User-Agents from the access log
map $http_user_agent $loggable {
    ~*(bot|crawler|spider|healthcheck)  0;
    default                             1;
}

# Decide the cache policy from the request path
map $uri $cache_control {
    ~*\.(js|css|woff2)$   "public, max-age=31536000, immutable";
    ~*\.html$             "no-cache";
    default               "no-store";
}
Using map variablesNGINX
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;
    }
}

Tip

  • A map can only be declared in the http context, and it is evaluated only when its value is actually used, so creating many maps costs almost nothing in performance.
  • $uri is the decoded, normalized current URI (it can change after an internal redirect), and $request_uri is the original URI + query sent by the client. Use $request_uri for redirects and $uri for file lookups.

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

Tip

If you leave out `proxy_set_header`, the backend application sees only the internal IP of Nginx instead of the real client IP β€” logs and rate limit keys go wrong, so always set it as well.

Advanced reverse proxying β€” keepalive, timeouts, WebSocket

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 / SSE
location /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 proxies
set_real_ip_from 10.0.0.0/8;          # internal LB range
set_real_ip_from 173.245.48.0/20;     # (example) CDN range β€” manage from the official list
real_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
SymptomMeaningSettings to check first
502 Bad GatewayCould not connect to the upstream, or the response was brokenThe upstream address/port, the backend process state, connect() failed in error.log
504 Gateway TimeoutThe upstream did not respond within the time limitproxy_read_timeout, slow queries on the backend
499 (in logs only)The client closed the connection before the responseWhether the client/LB timeout is shorter than that of Nginx
upstream sent too big headerThe response headers (cookies and so on) are larger than the bufferproxy_buffer_size 16k, proxy_buffers 8 16k

Tip

  • Non-idempotent requests such as POST are not retried by proxy_next_upstream by default (non_idempotent must be stated explicitly). Turning this option on for payment or order APIs can cause duplicate processing, so leave it off.
  • Trusting X-Forwarded-For as-is without set_real_ip_from lets a client forge the header to bypass IP-based blocking and rate limits. Always specify only the proxy ranges you trust.

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.
NGINX
location /static/ {
    alias /var/www/myapp/static/;
    expires 30d;
    add_header Cache-Control "public, immutable";
}

gzip on;
gzip_types text/css application/javascript application/json;
gzip_min_length 1024;

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.

1. Basic configurationNGINX
server {
    listen 80;
    server_name example.com;

    root /usr/share/nginx/html;

    # /images/product123.png β†’ /usr/share/nginx/html/images/product123.png
    location /images/ {
        try_files $uri /images/default.png;
    }
}
BehaviorTEXT
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;
    }
}
CheckBASH
nginx -t && nginx -s reload

curl -I http://example.com/images/product123.png
# HTTP/1.1 200 OK
# Content-Type: image/png
# Cache-Control: max-age=3600        ← real image: 1 hour

curl -I http://example.com/images/not-found.png
# HTTP/1.1 200 OK
# Content-Type: image/png
# Cache-Control: max-age=600         ← response replaced by the default image: 10 minutes
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;
}
ConfigurationWhen the image is missingWhen the default image is missing tooWhen to use
1. Basic try_files200 + default image500 (internal redirect cycle)The simplest setup
2. Dedicated location for the default image200 + default image (short cache)404Production (recommended)
3. alias + named location200 + default image404Files on a separate volume or in another directory
5. error_page404 + default image404When missing files have to be tracked by status code

Tip

  • Keep the cache time short for responses replaced by the default image. With a long cache, the default image stays in browsers and CDNs even after the real image is uploaded. Handling the default image in its own location, as in configuration 2, applies the short cache only to replaced responses.
  • Using expires together with add_header Cache-Control sends two Cache-Control headers (max-age=3600 and public). Use expires alone, or a single add_header Cache-Control "public, max-age=3600".
  • When the default image goes out with a 200, clients and search engines conclude that a real image exists at that address. If missing images have to be told apart, keep the 404 as in configuration 5.
  • When combining alias and try_files, end both the location and the alias with a slash (location /images/ and alias /data/uploads/). Leaving one off exposes the parent directory.
  • When checking, look beyond the status code: confirm that Content-Type is an image type such as image/png and that the body is the file you expect.

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;
}
Check (results from 1.20.2)BASH
# Before
curl -I http://example.com/images/photo.avif
# Content-Type: application/octet-stream

# After
curl -I http://example.com/images/photo.avif
# Content-Type: image/avif
Nginx 1.2x β€” adding headers in a locationNGINX
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
Item1.20 ~ 1.281.30Effect
try_files $uri /default-imageWorksWorksNo difference
Dedicated location for the default image (= /images/default.png)WorksWorksNo difference
alias + try_files + named locationWorksWorksNo difference
error_page 404 /default-imageWorksWorksNo difference
When the default image is missing500 (cycle detected)500 (cycle detected)No difference
MIME type for AVIF (mime.types)Missing in 1.20.2, present from 1.24.0PresentOn 1.20, .avif is sent as application/octet-stream, so the image is downloaded instead of displayed.
Controlling add_header inheritance (add_header_inherit)Not availableAvailable (added in 1.29.3)On older versions, an add_header in a location drops every add_header from the server block.

Tip

  • On Nginx 1.2x, use the default image configurations (1 to 5) as they are. No directive has to change because of the version.
  • If the types block added for 1.20 is left in place after upgrading to 1.24 or later, nginx -t prints a "duplicate extension avif" warning. It does no harm, and the block can be removed after the upgrade.
  • On 1.2x, when both server and location have add_header, check the real response headers with curl -I. Incidents where a security header is missing on one path only often come from this inheritance rule.
  • add_header_inherit is available in 1.30; on 1.28 and earlier nginx -t fails with an "unknown directive" error. If one configuration file is deployed to servers on several versions, use the old way (repeat the headers in the location).
  • Nginx fixes go only into the latest stable version. This configuration keeps working on 1.2x, but no more security patches arrive there, so plan an upgrade.

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.test
curl -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)CauseFix
Content-Type: application/octet-stream`.test` is not in mime.types and falls back to default_typePass it internally to the real .html with try_files/rewrite, or force default_type in the location
A Content-Disposition: attachment header is presentA header forcing download is set in a parent (server/http) contextRemove that add_header or limit it to the locations that need it
Content-Type is missing or emptyThe backend behind proxy_pass does not send the headerOverride it in nginx with proxy_hide_header + add_header

Tip

  • This configuration applies identically under `listen 80` and `listen 443 ssl` β€” the logic that decides Content-Type has nothing to do with HTTP/HTTPS, so if you serve both http and https server blocks, put the same location block in both.
  • `add_header` has the trait of blocking inheritance when the parent context already uses add_header β€” if the server block already has add_header directives, you have to write everything you need again in the location too.
  • After a change, always re-check that the actual headers changed: `sudo nginx -t && sudo nginx -s reload` β†’ `curl -I`.

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-nginx
sudo certbot --nginx -d example.com -d www.example.com
# The 80 β†’ 443 redirect and certificate settings are then added automatically
sudo 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 disabled
ssl_prefer_server_ciphers off;              # in the TLS 1.3 era, respect the client choice
ssl_session_cache   shared:SSL:10m;         # about 40,000 sessions β€” skips the handshake on reconnect
ssl_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 location
add_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-is
server {
    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 unchanged
server {
    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;
    }
}

Tip

  • For the configuration certbot generates, a systemd timer is registered alongside so the certificate renews automatically every 90 days. You can check it with `systemctl list-timers`.
  • From a security standpoint, the usual recommendation is for port 80 to do nothing but redirect to 443 with `return 301 https://$host$request_uri;` and to keep the real location logic only in the 443 block β€” but in a situation where you must also serve directly over http, keep identical locations in both blocks as above.
  • Let's Encrypt shut down its OCSP responder service in 2025, so the ssl_stapling on; setting found in older guides has no effect with those certificates. Consider it only when using certificates from another CA.
  • The TLS settings (ssl-params.conf) and the HSTS header (hsts.conf) are separated because of the inheritance rules. Directives such as ssl_certificate cannot be written inside a location, but adding even one add_header to a location makes the parent values disappear, so HSTS alone needs to be includable again separately.

Security hardening β€” headers, access control, rate limiting

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 IPs
limit_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 503
limit_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 optionBehaviorWhen to use it
rate=10r/sAllows 10 per second at even intervals (100ms)The average allowed rate
burst=20Queues up to 20 excess requestsAbsorbing normal traffic that bunches up briefly, as on page load
nodelayProcesses queued requests immediately, with no delayAPIs β€” when a fast response/fast rejection beats a delay
delay=8The first 8 immediately, the rest of the burst delayedA compromise between the two

Tip

  • When first introducing limit_req, use limit_req_dry_run on; to log without actually blocking, and check first whether normal users would be caught.
  • Users behind a corporate NAT or a mobile carrier share the same IP. For signed-in user APIs, also consider building the key with a map from an API key or a user identifying header instead of the IP.

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

Tip

  • When the backend sends a Set-Cookie or Cache-Control: private header, Nginx does not cache that response by default. If "caching is not working", check X-Cache-Status and the backend response headers first.
  • To clear the cache by force, delete the cache directory (open source Nginx has no purge directive). Putting a version string in the cache key at deploy time is also a common approach.

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
SettingDescription
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_cacheCaches the fd and metadata of static files to reduce stat() calls
proxy_buffers / proxy_buffer_sizeHandles large response headers and bodies in memory instead of on disk
limit_req_zone / limit_reqDefends against excessive traffic with per-IP rate limiting

Tip

As a next step, continue with packaging Nginx as a container in the docker guide, or with how an Ingress plays the same role inside a cluster in the kubernetes guide.

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 passes
sudo nginx -T | less                           # the full configuration actually loaded

# Vary the Host header to see which server block answers
curl -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
Temporary debug headersNGINX
location /api/ {
    add_header X-Debug-Location "api" always;
    add_header X-Debug-Upstream $upstream_addr always;
    # ...
}
# Always remove after checking (to avoid exposing internal addresses)
Error / log messageCauseFix
nginx: [emerg] unknown directiveA typo, or the module is not in the buildCheck the modules with nginx -V, check for a missing semicolon
conflicting server name ... ignoredThe same server_name is defined in two placesRemove the duplicate using nginx -T | grep server_name
403 ForbiddenNo index file in the directory, or insufficient file permissionsCheck 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 combinationCheck the path in "open() ... failed" in error.log
413 Request Entity Too LargeThe upload size exceeds client_max_body_sizeRaise the value in that server/location
502 + connect() failed (111: Connection refused)The backend is not running, or the port does not matchCheck the backend state and the upstream address
502 + (13: Permission denied) while connectingSELinux is blocking network connections from Nginxsetsebool -P httpd_can_network_connect 1
504 upstream timed outThe backend response exceeded proxy_read_timeoutSplit only the slow endpoints into their own location and adjust the timeout
rewrite or internal redirection cycletry_files/rewrite jumps to itself foreverUse =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.
/etc/nginx/nginx.confNGINX
user  nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;

events {
    worker_connections 8192;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    charset       utf-8;
    server_tokens off;

    sendfile on;  tcp_nopush on;  tcp_nodelay on;
    keepalive_timeout 65s;
    client_max_body_size 20m;
    client_body_timeout 30s;
    send_timeout 30s;
    reset_timedout_connection on;

    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_response_time":"$upstream_response_time","ua":"$http_user_agent"}';
    access_log /var/log/nginx/access.log json buffer=32k flush=5s;

    gzip on;  gzip_comp_level 5;  gzip_min_length 1024;
    gzip_proxied any;  gzip_vary on;
    gzip_types text/plain text/css application/javascript application/json
               application/xml image/svg+xml;

    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;

    limit_req_zone  $binary_remote_addr zone=api_rl:10m rate=10r/s;
    limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
    limit_req_status 429;
    limit_conn_status 429;

    proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:50m
                     max_size=2g inactive=30m use_temp_path=off;

    include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/example.com.confNGINX
upstream api_backend {
    least_conn;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=30s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=30s;
    keepalive 64;
}

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

# Block unknown Hosts
server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_reject_handshake on;
    return 444;
}

# http β†’ https
server {
    listen 80;
    server_name example.com www.example.com;
    location /.well-known/acme-challenge/ { root /var/www/certbot; }
    location / { return 301 https://example.com$request_uri; }
}

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

    include snippets/ssl-params.conf;
    include snippets/hsts.conf;
    include snippets/security-headers.conf;

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

    location ~ /\.(?!well-known/) { deny all; }

    # Hashed build output β€” cache for 1 year
    location ^~ /assets/ {
        include snippets/hsts.conf;              # guards against the add_header inheritance trap β€” include again
        include snippets/security-headers.conf;
        add_header Cache-Control "public, max-age=31536000, immutable";
        try_files $uri =404;
        access_log off;
    }

    location ^~ /api/ {
        limit_req  zone=api_rl burst=20 nodelay;
        limit_conn conn_per_ip 20;
        include snippets/proxy-headers.conf;
        proxy_set_header Connection "";
        proxy_connect_timeout 3s;
        proxy_read_timeout 30s;
        proxy_pass http://api_backend;
    }

    location ^~ /ws/ {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 1h;
    }

    # SPA routing
    location / {
        try_files $uri $uri/ /index.html;
    }
}

Tip

  • The reason hsts.conf and security-headers.conf are included again in the /assets/ location is that a single Cache-Control add_header makes every server-level header disappear (see the directive inheritance traps section).
  • Keeping the templates in Git and running a syntax check in CI with docker run --rm -v $PWD:/etc/nginx:ro nginx nginx -t blocks a bad configuration before it is deployed to a server.

Nginx: frequently asked questions

What is Nginx used for?

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.

← Previous guideInfrastructure Intro & RoadmapNext guide β†’Redis