当Nginx服务出现故障时,可以按照以下步骤进行排查和恢复:
systemctl status nginx # Systemd系统(CentOS 7+/Ubuntu 16.04+)
service nginx status # 旧版SysVinit系统
bash
sudo systemctl start nginx
Nginx日志通常位于:
tail -f /var/log/nginx/error.log # 实时查看错误日志
www-data
用户无权访问文件)sudo nginx -t
syntax is ok
,说明配置无语法错误。/etc/nginx/nginx.conf
或 /etc/nginx/sites-enabled/
)。sudo netstat -tulnp | grep 80
sudo lsof -i :80
确保Nginx用户(通常为www-data
或nginx
)有权限访问相关资源:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
bash
systemctl status php-fpm
bash
sudo ufw allow 80/tcp # Ubuntu
sudo firewall-cmd --add-port=80/tcp --permanent # CentOS
bash
setenforce 0 # 临时禁用(生产环境慎用)
检查系统资源是否耗尽:
free -h # 内存
df -h # 磁盘空间
top # CPU/进程
bash
cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
bash
sudo systemctl restart nginx
如果问题无法定位,尝试备份后重新安装:
sudo apt purge nginx && sudo apt install nginx # Debian/Ubuntu
sudo yum remove nginx && sudo yum install nginx # CentOS/RHEL
现象 | 可能原因 | 解决方案 |
---|---|---|
502 Bad Gateway | 后端服务未启动 | 检查PHP/Node.js等后端服务 |
403 Forbidden | 文件权限错误 | 调整目录权限或SELinux策略 |
404 Not Found | 路径配置错误 | 检查root 或alias 指令 |
端口占用 | Apache/其他服务冲突 | 停止冲突服务或修改Nginx端口 |
通过以上步骤,大部分Nginx问题可以快速解决。如果仍无法恢复,建议结合日志和系统监控工具深入分析。