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