nginx -t 是检查 Nginx 配置文件语法正确性的最直接有效方式,不启动服务、仅做静态解析和基础合法性校验,成功显示“syntax is ok”和“test is successful”,失败则明确提示错误文件、行号及原因(如 [emerg] unknown directive "lsten"),并能检测拼写错误、分号缺失、括号匹配、路径存在性等,但无法验证 SSL 证书、后端可达性、rewrite 循环或权限等运行时问题。
直接用 nginx -t 就能快速判断配置文件有没有硬伤,它不启动服务、不中断流量,只做静态解析和基础校验,是故障排查的第一步也是最关键的一步。
执行 nginx -t 后,输出会明确指出问题所在:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
nginx: [emerg] unknown directive "lsten" in /etc/nginx/conf.d/site.conf:10
这说明在 site.conf 第 10 行有个拼写错误(lsten 应为 listen)
[emerg] 表示紧急错误(配置无法加载),[warn] 是警告(可能影响功能但不阻断启动)线上常存在多套配置或自定义路径,不能只信默认路径:
ps aux | grep nginx,看启动命令是否含 -c 参数nginx -V 2>&1 | grep "conf-path"
nginx -t -c /opt/myapp/nginx.conf
nginx -t -p /opt/nginx/ -c /opt/nginx/conf/nginx.conf
nginx -t 能发现的,是改完配置后立刻暴露的问题;但它不负责“跑起来之后是否正常”:
指令拼写错误、分号遗漏、括号不匹配、include 的子配置文件不存在、root 或日志路径目录不存在、监听端口已被占用(基础检测)
SSL 证书文件损坏或过期、proxy_pass 后端服务器连不通、rewrite 规则导致无限重定向、worker 进程对日志目录无写权限
避免“一 reload 就挂”,把 -t 当作必经关卡:
nginx -t —— 不通过就别往下走nginx -s reload 或 systemctl reload nginx
nginx -t 输出,而不是盲目重启-q 参数可用于脚本集成:nginx -t -q || echo "配置有误,中止部署"