**修改 Nginx 配置后,永远先执行 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] directive "server_name" is not terminated by ";" in /etc/nginx/sites-enabled/example.com:3
每条指令都要以 ; 结尾。看报错的行号,以及它的上一行。
括号不匹配
nginx: [emerg] unexpected end of file, expecting "}" in /etc/nginx/sites-enabled/example.com:25
{ 和 } 没有成对。从报错位置往上检查每个 server、location 块。
未知指令
nginx: [emerg] unknown directive "proxy_pas" in ...
拼写错误,或者用到了当前 Nginx 没有编译的模块的指令(比如 Brotli)。
指令放错了位置
nginx: [emerg] "server" directive is not allowed here
比如把 server 块写到了另一个 server 块里,或者放在了 http 块之外。
重复的 default_server
nginx: [emerg] a duplicate default server for 0.0.0.0:80
多个站点都写了 listen 80 default_server;。只保留一个,常见于自定义了默认站点却没有删掉系统自带的 default。
重复的 server_name(警告)
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignored
两个配置文件里有同一个域名,后面的会被忽略。常见于复制配置后忘了改域名,或者同一个文件在 sites-enabled 中被链接了两次。
证书文件找不到
nginx: [emerg] cannot load certificate "/etc/letsencrypt/live/example.com/fullchain.pem": BIO_new_file() failed
证书路径错了,或证书还没申请。检查路径:
ls -l /etc/letsencrypt/live/
端口被占用(启动时)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
其他程序(Apache、另一个 Nginx、Docker 容器)占用了 80 端口:
ss -tlnp | grep ':80 '
小技巧
- 改配置前先备份:
cp example.com example.com.bak - 查看最终生效的完整配置:
nginx -T - 只
reload不restart:reload 时如果新配置有错,Nginx 会继续用旧配置运行,不会中断服务
还拿不准选哪款?
把业务类型、访问人群和预算告诉我们,工程师 7×24 在线,工单平均 10 分钟内响应。
