Nginx 常见问题总结与解决
1. 配置错误
- 现象:Nginx无法启动/重载。
- 原因:语法错误、路径错误。
- 解决 :
-
检查语法:
nginx -t
-
查看错误日志:
tail -f /var/log/nginx/error.log
-
路径问题 :区分
root
与alias
:nginxlocation /static/ { alias /data/www/static/; # 请求/static/img.png → /data/www/static/img.png } location /assets/ { root /data/www/; # 请求/assets/img.png → /data/www/assets/img.png }
-
2. 性能优化
- 现象:高并发下连接超限或响应慢。
- 解决 :
-
调整
nginx.conf
参数:nginxworker_processes auto; # 与CPU核心数一致 events { worker_connections 10240; # 单进程最大连接数 } http { keepalive_timeout 65; keepalive_requests 1000; }
-
修改系统文件描述符限制:
bashulimit -n 65535 # 临时生效 # 永久生效:编辑/etc/security/limits.conf,添加: # * soft nofile 65535 # * hard nofile 65535
-
3. 权限问题
- 现象:403 Forbidden。
- 解决 :
-
检查文件权限:
bashchmod -R 755 /data/www; chown -R www-data:www-data /data/www;
-
禁用SELinux(临时):
bashsetenforce 0 # 或修改/etc/selinux/config永久关闭
-
4. SSL证书问题
- 现象:浏览器提示证书错误。
- 解决 :
-
确保证书链完整(合并中间证书):
bashcat domain.crt intermediate.crt > fullchain.crt
-
配置SSL协议与加密套件:
nginxssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
-
5. 反向代理问题
- 现象:后端无法获取真实IP或超时。
- 解决 :
-
传递必要请求头:
nginxlocation / { 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 60s; proxy_read_timeout 60s; }
-
6. 负载均衡配置
- 现象:后端服务宕机未剔除。
- 解决 :
-
配置健康检查:
nginxupstream backend { server 10.0.0.1:80 max_fails=3 fail_timeout=30s; server 10.0.0.2:80; least_conn; # 可选策略:轮询(默认)、weight、ip_hash等 }
-
7. 静态文件服务
- 现象:静态资源404或SPA路由失效。
- 解决 :
-
使用
try_files
处理前端路由:nginxlocation / { root /data/www; try_files $uri $uri/ /index.html; }
-
8. 重写规则
- 现象:重定向循环或URL未生效。
- 解决 :
-
HTTP强制跳转HTTPS:
nginxserver { listen 80; server_name example.com; return 301 https://$host$request_uri; }
-
9. 跨域问题(CORS)
- 现象:前端请求跨域被拦截。
- 解决 :
-
添加响应头:
nginxlocation /api/ { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; }
-
10. WebSocket支持
- 现象:WebSocket连接失败。
- 解决 :
-
配置代理头:
nginxlocation /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
-
11. 安全加固
- 现象:服务器信息泄露。
- 解决 :
-
隐藏Nginx版本:
nginxserver_tokens off;
-
添加安全头:
nginxadd_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff;
-
12. 日志管理
- 现象:日志文件过大。
- 解决 :
-
使用
logrotate
配置轮转:bash# /etc/logrotate.d/nginx /var/log/nginx/*.log { daily rotate 30 compress missingok notifempty sharedscripts postrotate /usr/sbin/nginx -s reload endscript }
-
总结
遇到问题时,优先检查错误日志(error.log
),结合nginx -t
验证配置。复杂场景可通过分阶段调试(如逐步添加规则)定位问题根源。