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.

Web Services·41 commands·Last updated 2026-09-10
nginxReverse ProxylocationConfiguration

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 -t
Test config syntax, always run before reload
nginx -s reload
Graceful reload without dropping connections
nginx -T
Print full effective config, debug include conflicts
systemctl restart nginx
Full restart (drops connections), prefer reload
nginx -V
Show compile flags and enabled modules

Location Matching Priority 5

location = /path
Exact match, highest priority
location ^~ /static/
Prefix match, skip regex check
location ~ \.php$
Case-sensitive regex match
location ~* \.(jpg|png)$
Case-insensitive regex match
location /path
Regular prefix match, lowest priority

Reverse Proxy Snippets 5

proxy_pass http://127.0.0.1:8080;
Forward to backend, trailing slash affects path
proxy_set_header Host $host;
Pass original Host header
proxy_set_header X-Real-IP $remote_addr;
Pass real client IP
proxy_read_timeout 60s;
Backend response timeout, increase for 502 on long requests
client_max_body_size 50m;
Max upload size, increase for 413 errors

Logs & Troubleshooting 4

tail -f /var/log/nginx/error.log
Follow error log, check here first for 502/504
tail -f /var/log/nginx/access.log
Follow access log
grep " 502 " /var/log/nginx/access.log
Filter 502 requests
curl -I http://localhost
View response headers only, quick service check

Process Control & Performance (REQ-02 add-on) 22

nginx -g "daemon off;"
Run in foreground, common way to start nginx in containers
nginx -p /usr/local/nginx -c conf/nginx.conf
Specify prefix directory and config file
kill -s QUIT $(cat /var/run/nginx.pid)
Graceful stop by PID file (same as -s quit)
ps -ax | grep nginx
List nginx master and worker processes
nginx -e /var/log/nginx/error.log
Set error log path at startup
include /etc/nginx/conf.d/*.conf;
Include split-out config files
error_log /var/log/nginx/error.log warn;
Set error log path and severity level
pid /var/run/nginx.pid;
Specify master process PID file path
user nginx;
Set the user that worker processes run as
sendfile on;
Enable zero-copy sending for static files
tcp_nopush on;
Work with sendfile to reduce packets and raise throughput
keepalive_timeout 65;
Set keep-alive connection timeout
server_tokens off;
Hide version number to reduce info leakage
root /data/www;
Set the site root directory
index index.html index.htm;
Specify default index file order
location /images/ { root /data; }
Prefix-match a static directory with its own root
location ~ \.(gif|jpg|png)$ { root /data/images; }
Regex-match image extensions to a directory
fastcgi_pass localhost:9000;
Forward requests to a FastCGI backend
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
Set the FastCGI script path parameter
proxy_redirect off;
Disable rewriting of proxied redirect responses
proxy_connect_timeout 60s;
Timeout for establishing a connection to backend
stub_status;
Enable status page for connection and request stats

Parameter matrix

参数EffectExample
-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工作进程数,通常设为 autoworker_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. 1先校验配置语法

    nginx -t

    上线前必做,避免 reload 后整个服务起不来。

  2. 2平滑重载新配置

    nginx -s reload

    不中断现有连接;若旧 worker 卡死可用 -s quit 优雅退出。

  3. 3实时跟踪错误日志定位网关错误

    tail -f /var/log/nginx/error.log

    502/504/权限问题都会在 error.log 留下 connect()/permission 线索。

  4. 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