Nginx config
Goal
Produce a minimal config that does what the user needs and can be checked before it touches live traffic.
A good result states what each block does so the next person can change it.
When to use
- A reverse proxy in front of an app is needed.
- Requests fail with 502, 504, 413 or redirect loops.
- TLS, HTTP to HTTPS redirect or websockets need setting up.
- For host level SSH access, use
use_skillwithssh-hardening-setup.
Steps
- Read the current config. Use
lson the nginx config folder andread_fileonnginx.confand included site files. - Ask or detect the upstream: host, port, protocol and whether the app expects forwarded headers.
- Write a
serverblock withserver_name,listen, andlocationblocks. Usecreate_filefor a new site file rather than growingnginx.conf. - Proxy with
proxy_passand setHost,X-Real-IP,X-Forwarded-ForandX-Forwarded-Proto. Check the trailing slash behaviour ofproxy_passbefore writing the path. - For websockets add the
UpgradeandConnectionheaders andproxy_http_version 1.1, and a read timeout above idle gaps. - For TLS point to certificate files, redirect port 80 to HTTPS, and take the cipher and protocol settings from a current recommendation. Fetch it with
read_urlfrom the Mozilla SSL config generator page rather than recalling. - Add
client_max_body_sizefor uploads and sensible timeouts. Add gzip and cache headers for static files withlocationblocks. - Set security headers and hide the server version with
server_tokens off. - Validate with
nginx -tthroughrun_command(or the docker equivalent) before any reload. - Reload with
nginx -s reload, not restart, then test withcurl -Ifor status, redirects and headers. - Debug errors in the error log with
read_fileorrun_commandtail, and match the message to the cause. - Save the final config and describe each block.
Gotchas
- A trailing slash on
proxy_passchanges how the request path is rewritten, and gives surprising 404s. ifinsidelocationis unreliable. Prefermap,try_filesor separate locations.- 502 with the upstream running is often the upstream listening on 127.0.0.1 inside another container, or an SELinux rule.
- The default body limit is small, so uploads fail with 413 before reaching the app.
- Nginx resolves upstream hostnames once at start. When the container IP changes, it keeps the old one unless a resolver and variable are used.
- Setting
X-Forwarded-Forfrom client supplied input lets users spoof their address.
Output
- The config file path and the complete block that was added, with short comments.
- The
nginx -tresult. - The curl checks run and what they showed.
