Nginx Cheatsheet - Nginx Configuration & Command Reference
For engineers debugging 502/504s, adjusting location routing, or setting up reverse proxies. The hard part of Nginx is not the sheer number of directives but the details — location matching rules, whether proxy_pass carries a trailing slash, and upstream timeout tuning — which fail silently and only surface as anomalies under traffic. By the end you will validate with nginx -t before reloading, trace upstream errors back to the backend from the error log, and tell apart 502 Bad Gateway from 504 Gateway Timeout.
Typical Use Case
Configure reverse proxy, load balancing, static file serving and TLS termination; troubleshoot 502/504 gateway errors, redirect loops, config syntax errors, and permission denied (13: Permission denied).
Commands & Testing 5
nginx -tnginx -s reloadnginx -Tsystemctl restart nginxnginx -VLocation Matching Priority 5
location = /pathlocation ^~ /static/location ~ \.php$location ~* \.(jpg|png)$location /pathReverse Proxy Snippets 5
proxy_pass http://127.0.0.1:8080;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_read_timeout 60s;client_max_body_size 50m;Logs & Troubleshooting 4
tail -f /var/log/nginx/error.logtail -f /var/log/nginx/access.loggrep " 502 " /var/log/nginx/access.logcurl -I http://localhostProcess Control & Performance (REQ-02 add-on) 22
nginx -g "daemon off;"nginx -p /usr/local/nginx -c conf/nginx.confkill -s QUIT $(cat /var/run/nginx.pid)ps -ax | grep nginxnginx -e /var/log/nginx/error.loginclude /etc/nginx/conf.d/*.conf;error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;user nginx;sendfile on;tcp_nopush on;keepalive_timeout 65;server_tokens off;root /data/www;index index.html index.htm;location /images/ { root /data; }location ~ \.(gif|jpg|png)$ { root /data/images; }fastcgi_pass localhost:9000;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;proxy_redirect off;proxy_connect_timeout 60s;stub_status;Parameter matrix
| 参数 | Effect | Example |
|---|---|---|
-t | 仅测试配置文件语法,不启动 | nginx -t |
-s reload | 平滑重载配置(不中断连接) | nginx -s reload |
-s stop | 快速停止 | nginx -s stop |
-c | 指定配置文件路径 | nginx -c /etc/nginx/nginx.conf |
-g | 启动时传入全局指令 | nginx -g 'daemon off;' |
worker_processes | 工作进程数,通常设为 auto | worker_processes auto; |
proxy_pass | 将请求转发到上游服务 | proxy_pass http://127.0.0.1:3000; |
upstream | 定义后端服务器池做负载均衡 | upstream app { server 10.0.0.1; } |
try_files | 按序尝试文件,最后回退 | try_files $uri $uri/ /index.html; |
return 301 | 返回重定向 | return 301 https://$host$request_uri; |
Common pitfalls
Symptom改完配置不生效或新旧配置混用。
Cause改了文件却忘记 reload,或直接改了正在运行的 worker 内存。
Fix每次改完先 nginx -t 校验语法,再 nginx -s reload 平滑生效;避免 kill 掉 worker 造成连接中断。
Symptom访问站点返回 502 Bad Gateway。
Cause上游(proxy_pass 指向的后端)未启动、端口错或连接被防火墙拦截。
Fix在 nginx 主机上 curl 直连上游验证可用性;检查 upstream 地址/端口与后端监听;看 error.log 的 connect() failed。
Symptom返回 504 Gateway Timeout。
Cause上游响应超过 proxy_read_timeout(默认 60s)。
Fix调大 proxy_read_timeout / proxy_send_timeout,或优化上游处理耗时;确认不是上游死锁。
Symptom静态文件返回 403 Forbidden,日志 13: Permission denied。
Causenginx 工作进程用户(如 www-data)无目录/文件读权限,或 SELinux 限制。
Fix确认目录有 o+x、文件有 o+r;若启用 SELinux 用 setsebool -P httpd_read_user_content 1 放行。
SymptomHTTP 被强制跳转到 HTTPS 形成重定向循环。
CauseSSL 终端在 CDN/负载均衡层已做 443 跳转,nginx 又再跳一次。
Fix确认跳转只在一层发生;若 CDN 已终止 TLS,nginx 侧不要再 return 301 https。
Symptom配置测试报错 unknown directive。
Cause使用了未编译进二进制的模块(如未装 stub_status、lua)。
Fixnginx -V 看编译模块;缺失时换用带该模块的包或重新编译,不要在配置里引用不存在的指令。
Troubleshooting
1先校验配置语法
nginx -t上线前必做,避免 reload 后整个服务起不来。
2平滑重载新配置
nginx -s reload不中断现有连接;若旧 worker 卡死可用 -s quit 优雅退出。
3实时跟踪错误日志定位网关错误
tail -f /var/log/nginx/error.log502/504/权限问题都会在 error.log 留下 connect()/permission 线索。
4从 nginx 主机直连上游验证可用性
curl -I http://127.0.0.1:3000/health排除是上游挂了还是 nginx 配置问题。
Tips
- Trailing slash in proxy_pass changes semantics: with / replaces location prefix, without it appends.
- Always run nginx -t before reload — a syntax error won't break the running process but reload won't apply.
- For 502: check error.log — "connection refused" means backend is down, "timeout" means backend is too slow.
FAQ
How does Nginx decide the order of location matching?
Priority from highest to lowest: exact match with =, then the ^~ prefix (which stops without checking regexes), then regex ~/~* (the first matching regex wins, in config order), and finally plain longest-prefix matching. Both = and ^~ short-circuit immediately, while regex matching waits until all prefix locations have been tried.
When I get a 404, how do I tell whether the location did not match or the backend really returned 404?
Check the error log. If the request never reached the backend, you will only see an access entry, and the proxy_pass target server receives no request; if the backend returned 404, the log shows the upstream response to the backend request. You can also temporarily add a try_files rule or directly curl the backend port to compare.
What is the difference between proxy_pass with and without a trailing slash?
The key difference is path handling. When proxy_pass includes a URI such as http://upstream/api/, the part of the request that matched the location is appended to that path; when it has no URI (http://upstream or http://upstream/), the original request URI is passed through unchanged. Adding a path is how you rewrite /foo to a backend prefix like /api/... .
How do I troubleshoot a 502 Bad Gateway vs a 504 Gateway Timeout?
A 502 means Nginx could not get a valid response from the backend: first confirm the process is alive, the port is listening, and firewall and proxy_pass address are correct. A 504 means the backend exceeded the configured timeout, so check backend processing time first, then raise proxy_read_timeout/proxy_connect_timeout. Always cross-reference the upstream section of the error log in both cases.
Should I restart or reload after changing Nginx config?
Prefer nginx -s reload or systemctl reload nginx: it reloads gracefully without dropping existing connections and validates the config first. Only fall back to systemctl restart when the change touches parameters that cannot be hot-reloaded, such as listen sockets or worker counts, or when reload keeps failing. Always run nginx -t first.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Sep 10, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us