Ubuntu 上 Nginx 错误代码排查与修复
一、快速定位与通用排查
二、常见错误代码与修复对照表
| 错误码或报错 | 典型原因 | 快速修复 |
|---|---|---|
| 403 Forbidden | 目录无索引且未开启目录列表;文件/目录权限或属主不对;Nginx 用户无访问权 | 在对应 location 添加 index index.html index.php; 或开启 autoindex on;;修正权限 chmod -R 755 /var/www/html,chown -R www-data:www-data /var/www/html;确认 /etc/nginx/nginx.conf 中的 user www-data; 与目录属主一致 |
| 404 Not Found | root/alias 路径错误;请求的文件不存在;未使用 try_files | 核对 root 是否指向正确目录;确认文件存在;在 location 中使用 try_files $uri $uri/ =404; |
| 500 Internal Server Error | 后端脚本异常(如 PHP 致命错误);磁盘空间满;文件句柄数限制过低;配置语法/路径错误 | 查看 /var/log/nginx/error.log 定位具体行;执行 df -lh 检查磁盘;提升句柄数:ulimit -n 65535,在 /etc/security/limits.conf 设置 soft/hard nofile 65535,在 /etc/sysctl.conf 设置 fs.file-max=65536,在 /etc/nginx/nginx.conf 的 worker_processes 后添加 worker_rlimit_nofile 65535;;用 nginx -t 检查配置与路径 |
| 502 Bad Gateway | 上游服务(如 PHP-FPM/Node.js)未启动或端口不对;连接被拒/超时;防火墙阻断 | 确认上游运行:systemctl status php-fpm 或 **ps aux |
| 503 Service Unavailable | 上游过载或崩溃;反向代理 max_fails/fail_timeout 触发熔断 | 检查上游健康与负载;优化或扩容上游;在 upstream 中调整 max_fails、fail_timeout 并重试 |
| 504 Gateway Timeout | 上游处理耗时过长;Nginx 超时过短 | 增大 proxy_read_timeout / proxy_connect_timeout;优化上游性能或异步化处理 |
| SSL 相关错误(如证书不匹配) | 证书/私钥不匹配或证书过期;TLS 配置不当 | 核对 ssl_certificate 与 ssl_certificate_key 是否匹配且未过期;可用 openssl s_client -connect yourdomain.com:443 -servername yourdomain.com 测试;必要时用 certbot --nginx -d yourdomain.com 重新签发 |
| 端口被占用(启动报错:bind() to 0.0.0.0:80 failed (98: Address already in use)) | 其他服务(如 apache2)占用 80/443 | 查占用进程 **netstat -tulnp |
| 配置文件语法错误(如 unknown directive) | 指令拼写错误、缺少分号/括号、路径错误 | 执行 sudo nginx -t 定位文件与行号;修正语法与路径后重载 sudo systemctl reload nginx |
三、实用命令清单
四、最小可用配置示例
server {
listen 80;
server_name your.domain local.test;
root /var/www/html;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass 127.0.0.1:9000; # 与 PHP-FPM 一致
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
upstream backend {
server 127.0.0.1:3000;
# 可按需增加 max_fails/fail_timeout
}
server {
listen 80;
server_name api.local;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
}
}
修改后执行:sudo nginx -t && sudo systemctl reload nginx。