现象:Nginx无法启动或重载(如systemctl restart nginx失败),提示“syntax error”“unexpected ‘}’”等。
解决方法:
nginx -t命令测试配置文件语法,错误信息会明确指出错误文件及行号(如“/etc/nginx/sites-available/example.conf:3”);roo代替root)、缺少必要分号(如listen 80后无分号)、配置块嵌套错误(如server块写在location块内)、参数无效(如index 1.php 2.html中文件不存在);nginx -t,确认提示“syntax is ok”和“test is successful”后再重载配置(systemctl reload nginx)。现象:访问网站时返回403 Forbidden,或Nginx无法读取日志、静态文件。
解决方法:
www-data或nginx)对网站目录及文件有读取权限,使用chmod -R 755 /path/to/website设置目录权限,chown -R www-data:www-data /path/to/website设置属主属组;setenforce 0)或永久修改/etc/selinux/config(将SELINUX=enforcing改为disabled);/var/log/nginx/目录可写(chmod 755 /var/log/nginx/)。现象:访问静态资源(如图片、CSS、JS)返回404 Not Found。
解决方法:
root/alias配置:root指令指定文件系统路径(如root /var/www/html;,请求/img.png对应/var/www/html/img.png);alias指令用于路径别名(如location /static/ { alias /data/www/static/; },请求/static/img.png对应/data/www/static/img.png),注意alias需用绝对路径;location块覆盖静态文件规则(如更具体的location块应放在前面)。现象:访问网站时返回502(Bad Gateway,后端服务不可用)或504(Gateway Timeout,后端响应超时)。
解决方法:
systemctl status php-fpm),确保Nginx能访问后端(telnet backend_ip 9000测试端口);确认proxy_pass指令指向正确的后端地址(如proxy_pass http://backend;);proxy_connect_timeout 60s;、proxy_read_timeout 60s;),增加后端响应时间限制;检查后端服务性能(如数据库查询慢、代码逻辑问题)。现象:执行systemctl start nginx或systemctl reload nginx失败,无具体错误提示。
解决方法:
netstat -tuln | grep ':80'或ss -tuln | grep ':80'查看80/443端口是否被其他程序占用(如Apache),终止占用进程(kill -9 pid)或修改Nginx监听端口(listen 8080;);nginx -t测试配置,避免因语法错误导致无法启动;tail -f /var/log/nginx/error.log获取详细错误信息(如权限不足、路径不存在)。现象:浏览器访问HTTPS网站提示“证书无效”“不安全连接”。
解决方法:
domain.crt和intermediate.crt为fullchain.crt,命令:cat domain.crt intermediate.crt > fullchain.crt);ssl_certificate /path/to/fullchain.crt;、ssl_certificate_key /path/to/domain.key;);ssl_protocols TLSv1.2 TLSv1.3;)和加密套件(ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;)。现象:后端服务器(如PHP、Node.js)获取的客户端IP为Nginx服务器IP(如127.0.0.1)。
解决方法:
location块中添加proxy_set_header指令,传递真实IP: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;
}
其中X-Real-IP直接传递客户端IP,X-Forwarded-For记录代理链路中的所有IP。现象:后端某台服务器宕机,但Nginx仍向其转发请求,导致请求失败。
解决方法:
upstream块中配置健康检查参数:upstream backend {
server 10.0.0.1:80 max_fails=3 fail_timeout=30s; # 3次失败后标记为不可用,30秒后重试
server 10.0.0.2:80;
least_conn; # 可选:使用最少连接策略
}
max_fails指定失败次数,fail_timeout指定超时时间,超过阈值的后端会被自动剔除。现象:刷新SPA页面(如Vue、React)时返回404,或路由跳转异常。
解决方法:
try_files指令将所有请求重定向到index.html,由前端框架处理路由:location / {
root /data/www/spa;
try_files $uri $uri/ /index.html;
}
这样,当访问/about时,若/about路径不存在,会返回index.html,前端再根据路由渲染对应组件。现象:访问网站时出现无限重定向(如HTTP→HTTPS→HTTP),导致浏览器提示“ERR_TOO_MANY_REDIRECTS”。
解决方法:
return指令仅应用于HTTP监听的server块:server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri; # 仅HTTP重定向到HTTPS
}
server {
listen 443 ssl;
server_name example.com;
# HTTPS配置
}
避免在HTTPS的server块中再次添加HTTP重定向规则。