/etc/nginx/ tree and 00-–08- load order
Once a server hosts more than one site, assemble the configs from individual guides into one clean tree with clear boundaries: global defaults in 00-–08-, reusable snippets in snippets/, one file per domain, and L4 rules in stream.d/.
/etc/nginx/
├── nginx.conf # thin skeleton: workers, events, http, stream
├── mime.types # package MIME types (leave untouched)
├── snippets/ # NOT auto-loaded — explicit include only
│ ├── tls.conf # TLS 1.2/1.3 and shared session cache
│ ├── headers.conf # X-Content-Type-Options, X-Frame-Options, CSP
│ └── proxy-headers.conf # proxy_http_version 1.1, Host, X-Real-IP, X-Forwarded-*
├── conf.d/ # included inside http {} in alphabetical order (*.conf)
│ ├── 00-default.conf # default_server catch-alls on :80 (444) and :443 (reject)
│ ├── 01-hardening.conf # server_tokens off, timeouts, body and header limits
│ ├── 02-maps.conf # shared maps: WebSocket ($connection_upgrade), CORS, redirects
│ ├── 02-realip.conf # only when behind Cloudflare or another proxy
│ ├── 03-ratelimit.conf # geo/map exemptions and limit_req_zone / limit_conn_zone
│ ├── 04-performance.conf # sendfile, tcp_nopush, tcp_nodelay, open_file_cache
│ ├── 05-compression.conf # gzip, gzip_static, gzip_types
│ ├── 06-logging.conf # log_format json_timing, map $loggable, access_log
│ ├── 07-bots.conf # map $bad_bot, $bots_welcome, $deny_bot
│ ├── 08-status.conf # stub_status on 127.0.0.1:8081 only
│ ├── app.example.org.conf # reverse proxy + WebSocket
│ ├── example.org.conf # static site / SPA
│ └── old.example.org.conf.disabled # disabled site — skipped by *.conf
└── stream.d/ # included inside stream {} (outside http!)
└── postgres-sni.conf # when using TCP/UDP or SNI routing
On Linux, include /etc/nginx/conf.d/*.conf; reads files alphabetically, so the 00-–08- numeric prefixes solve three things at once:
log_formatmust load before anyaccess_logthat references it:06-logging.confalways comes before domain filesa…z.00-default.confalways loads first on ports 80 and 443 — even ifdefault_serveris accidentally removed somewhere, the catch-all stays the first block rather than a live site.- Global plumbing stays separate from sites: in
ls /etc/nginx/conf.d/andnginx -T, shared rules sit neatly at the top and domains follow in alphabetical order.
File in conf.d/ |
What it sets | Line-by-line guide |
|---|---|---|
00-default.conf |
Drops unknown Host (444) and unknown SNI (ssl_reject_handshake) |
Hardening, HTTPS & HTTP/3 |
01-hardening.conf |
server_tokens off, Slowloris timeouts, body and header limits |
Hardening |
02-maps.conf, 02-realip.conf |
map tables (WebSocket, CORS, redirects) and trusted proxy subnets |
Reverse proxy, CORS & preflight, Limits & access |
03-ratelimit.conf |
limit_req_zone and limit_conn_zone, 429 status |
Limits & access |
04-performance.conf |
sendfile, tcp_nopush, tcp_nodelay, open_file_cache |
Tuning & compression |
05-compression.conf |
gzip, gzip_static, text MIME types |
Tuning & compression |
06-logging.conf |
log_format json_timing, /healthz filter, buffered access_log |
Logs & debugging |
07-bots.conf |
Bad-bot filter via map while keeping /robots.txt open |
Bots & WAF |
08-status.conf |
Local /nginx_status on 127.0.0.1:8081 |
Logs & debugging |
Skip any file your server doesn’t need (for example 02-realip.conf without Cloudflare or stream.d/ without L4 proxying) — the other layers have no hard dependency on it.
Thin /etc/nginx/nginx.conf with no duplicates
The most common failure when assembling this tree is leaving the stock /etc/nginx/nginx.conf untouched. The default nginx.org file already puts sendfile on;, keepalive_timeout 65;, log_format main, and access_log inside http {}. Drop 01-hardening.conf, 04-performance.conf, and 06-logging.conf on top, and nginx -t fails immediately with directive is duplicate — or two access_log directives write every request twice.
Strip nginx.conf down to a thin skeleton holding only process settings, the descriptor limit, mime.types, and two include lines.
user nginx;
worker_processes auto;
worker_rlimit_nofile 16384;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 4096;
}The nginx.org package runs workers as nginx (Ubuntu’s distro package uses www-data, Install & layout). worker_rlimit_nofile keeps the open-socket ceiling well above worker_connections (Tuning & compression).
default:worker_processes 1worker_connections 512
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
}Inside http {} there is intentionally no sendfile, keepalive_timeout, gzip, or access_log: each directive lives in exactly one file under conf.d/01-–06-. Every file in conf.d/ is already inside http {}.
stream {
include /etc/nginx/stream.d/*.conf;
}Top-level stream {} block for TCP/UDP and SNI routing without decryption (TCP/UDP stream). An empty /etc/nginx/stream.d/ directory causes no error with *.conf; drop the block entirely if you don’t use stream.
Compatibility rules for the three files in /etc/nginx/snippets/
Unlike conf.d/, you create /etc/nginx/snippets/ manually (sudo mkdir -p /etc/nginx/snippets), and nginx never auto-loads it — each snippet applies only where included. Keep three compatibility rules in mind when combining them on one host:
snippets/tls.conf(HTTPS & HTTP/3) — include in every HTTPSserverblock. Havingssl_session_cache shared:SSL:10m;inside the snippet works safely across dozens ofserverblocks because they all share the sameSSLzone without conflict.snippets/headers.conf(Hardening) — include inserver {}and repeat in everylocationthat defines its ownadd_header(such as/assets/caching or CORS headers in CORS & preflight). Otherwise list-based inheritance drops all security headers on that route (add_header inheritance).snippets/proxy-headers.conf(Reverse proxy) — include only inside the proxiedlocation, right beforeproxy_set_header Connection ...;. Never place it at theserver {}level: a singleproxy_set_header Connection "";insidelocationwould wipeHost,X-Real-IP, andX-Forwarded-*inherited fromserver. For S3/MinIO, where SigV4 signatures require the originalHost $http_host, write the headers explicitly instead of using this snippet (Large uploads & S3).
Two production sites on top of the layout
Below are the 00-default.conf catch-all (after deleting the stock /etc/nginx/conf.d/default.conf) and two sites layered on top of the tree: static example.org and proxied app.example.org with WebSocket and keepalive.
# /etc/nginx/conf.d/00-default.conf
server {
listen 80 default_server;
server_name _;
return 444;
}
server {
listen 443 ssl default_server;
server_name _;
ssl_reject_handshake on;
}Combined catch-all on both ports in /etc/nginx/conf.d/00-default.conf: drops direct-IP and unknown-domain traffic without exposing any live site’s certificate. Remove the stock /etc/nginx/conf.d/default.conf first.
# /etc/nginx/conf.d/example.org.conf
server {
listen 80;
server_name example.org www.example.org;
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://example.org$request_uri;
}
}
server {
listen 443 ssl;
http2 on;
server_name example.org;
ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem;
include snippets/tls.conf;
include snippets/headers.conf;
root /var/www/example.org;
index index.html;
if ($deny_bot) {
return 403;
}
limit_req zone=site_limit burst=20 nodelay;
limit_conn per_ip_conn 20;
location = /healthz {
return 200 "ok\n";
}
location /assets/ {
include snippets/headers.conf;
add_header Cache-Control "public, max-age=31536000, immutable" always;
}
location ~ /\.(?!well-known) {
deny all;
}
location / {
try_files $uri $uri/ =404;
}
}Static site /etc/nginx/conf.d/example.org.conf: HTTP redirect with a Let's Encrypt exception, TLS 1.2/1.3 and HTTP/2, shared security headers, bot filtering from 07-bots.conf, and rate limits from 03-ratelimit.conf. /assets/ re-includes headers.conf so Cache-Control doesn’t wipe CSP and the rest.
# /etc/nginx/conf.d/app.example.org.conf
upstream app_backend {
server 127.0.0.1:3000;
keepalive 32;
}
server {
listen 443 ssl;
http2 on;
server_name app.example.org;
ssl_certificate /etc/letsencrypt/live/app.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.example.org/privkey.pem;
include snippets/tls.conf;
include snippets/headers.conf;
client_max_body_size 16m;
if ($deny_bot) {
return 403;
}
location / {
include snippets/proxy-headers.conf;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://app_backend;
}
}Reverse proxy /etc/nginx/conf.d/app.example.org.conf: upstream pool with keepalive and a local client_max_body_size 16m overriding the global 1m from 01-hardening.conf. proxy-headers.conf sits inside location / alongside $connection_upgrade from 02-maps.conf — one block handles both keepalive (variable stays empty on plain HTTP) and WebSocket.
How to check
- Check syntax, duplicate directives, and exact file load order (confirm
default.confis gone and00-–08-appear before site configs):sudo nginx -t sudo nginx -T 2>/dev/null | grep '^# configuration file' sudo systemctl reload nginx - Test the
default_servercatch-all on both ports:curl -sS -H "Host: unknown.invalid" http://127.0.0.1/ # curl: (52) Empty reply from server curl -sS --resolve unknown.invalid:443:127.0.0.1 https://unknown.invalid/ # OpenSSL: ... tlsv1 unrecognized name - Confirm
/assets/returnsgzip,Cache-Control, hidden version (server: nginx), and every security header fromsnippets/headers.conf:curl -sSI -H "Accept-Encoding: gzip" https://example.org/assets/app.js \ | grep -iE '^(HTTP/|server:|content-encoding:|cache-control:|x-content-type-options:|content-security-policy:)' - Test the bot filter (
403on/,200on/robots.txt), the JSON log without/healthznoise, and localstub_status:curl -s -o /dev/null -w "%{http_code}\n" -A "GPTBot/1.0" https://example.org/ # 403 curl -s -o /dev/null -w "%{http_code}\n" -A "GPTBot/1.0" https://example.org/robots.txt # 200 curl -s http://127.0.0.1:8081/nginx_status sudo tail -n 5 /var/log/nginx/access.log
If it doesn’t work
nginx -t fails with "keepalive_timeout" directive is duplicate or "sendfile" directive is duplicate
- Cause
- The stock
/etc/nginx/nginx.conffromnginx.orgalready definessendfile on;andkeepalive_timeout 65;, which collide withconf.d/01-hardening.confor04-performance.confat the samehttplevel. - Fix
- Remove duplicate directives from
http {}innginx.confand keep each global setting in exactly one file.
nginx -t fails with unknown log format "json_timing"
- Cause
- An
access_logdirective referencing that format appeared beforelog_format json_timingwas declared — for instance, left insidenginx.confaboveinclude /etc/nginx/conf.d/*.conf;. - Fix
- Keep
log_formatand the defaultaccess_logtogether inconf.d/06-logging.conf, which loads before any domain configa…z.
nginx -t fails with a duplicate default server for 0.0.0.0:80 or :443
- Cause
- The stock
/etc/nginx/conf.d/default.confis still present alongside00-default.conf, or a second site setsdefault_serveron the same port. - Fix
- Delete the stock
default.confand keep a singledefault_serverper port (80 and 443) inside00-default.conf(default_server catch-all).
nginx -t fails with "stream" directive is not allowed here
- Cause
- A TCP/UDP proxy config containing
stream { ... }was placed in/etc/nginx/conf.d/, which is included insidehttp {}. - Fix
- Move L4 configs into
/etc/nginx/stream.d/*.confand include them from a top-levelstream {}block innginx.conf(TCP/UDP stream).
Security headers from snippets/headers.conf vanished on /assets/, or a proxied backend stopped receiving Host and X-Real-IP
- Cause
add_headerandproxy_set_headerinherit as whole lists: a single directive of that type inside alocationdrops every directive of the same type fromserver(add_header inheritance).- Fix
- Repeat
include snippets/headers.conf;inside everylocationthat sets its ownadd_header, and always placeinclude snippets/proxy-headers.conf;inside the proxiedlocationnext toproxy_set_header Connection.
You added a new site file in conf.d/ and reloaded nginx, yet the site didn’t load
- Cause
include /etc/nginx/conf.d/*.conf;loads only files ending in.conf(Ubuntu’s distro package also requires a symlink insites-enabled/).- Fix
- List the loaded config files with
sudo nginx -T 2>/dev/null | grep '^# configuration file'and check the filename extension.