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 致命错误);磁盘满;文件句柄数过低;配置路径错误 | 查看 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; |
| 502 Bad Gateway | 上游(如 PHP-FPM/Node.js)未启动或端口不对;连接被拒/超时;防火墙阻断 | 确认上游运行:systemctl status php-fpm;核对 fastcgi_pass/proxy_pass 地址端口;必要时开放防火墙端口 |
| 503 Service Unavailable | 上游过载或崩溃;反向代理 max_fails/fail_timeout 触发熔断 | 检查上游健康与负载;在 upstream 中调整 max_fails、fail_timeout 并重试 |
| 504 Gateway Timeout | 上游处理耗时过长;Nginx 超时过短 | 增大 proxy_connect_timeout / proxy_read_timeout;优化上游性能或异步化 |
| SSL 证书错误 | 证书/私钥不匹配或过期;TLS 配置不当 | 核对 ssl_certificate 与 ssl_certificate_key 是否匹配且未过期;用 openssl s_client -connect yourdomain.com:443 -servername yourdomain.com 测试;必要时 certbot --nginx -d yourdomain.com 重签 |
| 端口被占用 | 其他服务(如 apache2)占用 80/443 | 查占用进程并停止,或把 Nginx 改为 listen 8080; 后再 reload |
| 配置不生效(仍是 welcome to nginx) | 站点未启用或配置未包含;修改未重载 | 确认 /etc/nginx/sites-enabled/ 下已存在你的站点配置(或已删除默认配置的符号链接);执行 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;
}
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。
四、使配置生效与安全放行
五、仍未解决时的进阶建议