网站反代服务器出现报错 500 Internal Server Error

让我们逐步排查 Nginx 500 内部错误的可能原因:

  1. 查看错误日志
bash
# 默认错误日志位置
tail -f /var/log/nginx/error.log

# 或自定义错误日志位置
tail -f /usr/local/nginx/logs/error.log

  1. 常见原因和解决方案:
  • PHP-FPM 配置问题
nginx
# 检查 php-fpm 是否运行
systemctl status php-fpm

# 检查 nginx 配置中的 fastcgi_pass 是否正确
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 确认socket路径正确
# 或
fastcgi_pass 127.0.0.1:9000; # 确认端口正确
}
  • 权限问题
bash
# 检查目录权限
chmod 755 /var/www/html
chown -R www-data:www-data /var/www/html

# 检查日志文件权限
chmod 755 /var/log/nginx

  • 反代配置问题
nginx
# 检查上游服务器配置
upstream backend {
server backend.example.com:8080;
}

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

  • SELinux 问题
bash
# 临时关闭 SELinux 测试
setenforce 0

# 查看 SELinux 状态
getenforce

能否提供错误日志内容?这样可以更准确地定位问题。

socket() failed (24: Too many open files) while connecting to upstream

这个错误表示打开的文件句柄数达到了系统限制。需要从两个方面增加限制:

  1. 增加系统文件句柄限制:
bash
# 编辑 /etc/security/limits.conf,添加
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535

# 编辑 /etc/sysctl.conf,添加
fs.file-max = 65535

# 应用 sysctl 设置
sysctl -p

  1. 修改 Nginx 配置:
nginx
# nginx.conf 主配置文件
worker_rlimit_nofile 65535; # 增加 worker 进程的文件句柄限制

events {
worker_connections 65535; # 增加每个 worker 的最大连接数
}

  1. 验证修改:
bash
# 检查当前系统限制
ulimit -n

# 重启 Nginx
systemctl restart nginx

# 检查 Nginx 进程的文件句柄限制
cat /proc/nginx进程id/limits

修改完成后需要重启系统使所有修改生效。如果问题持续,建议检查:

  • 实际并发连接数
  • 是否存在连接未正常释放的情况
  • 后端服务器的响应时间