From 3192a289af8aa68db05cc5322d136cf77366ce46 Mon Sep 17 00:00:00 2001 From: xiaoshuai Date: Mon, 11 May 2026 13:20:47 +0800 Subject: [PATCH] =?UTF-8?q?fix(nginx):=20=E8=A1=A5=E5=85=85=E5=8F=8D?= =?UTF-8?q?=E5=90=91=E4=BB=A3=E7=90=86=E6=95=85=E9=9A=9C=E6=8E=92=E6=9F=A5?= =?UTF-8?q?=E5=92=8C=20proxy=5Fpass=20=E9=99=B7=E9=98=B1=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nginx/SKILL.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/nginx/SKILL.md b/nginx/SKILL.md index d792ecb..e9829ba 100644 --- a/nginx/SKILL.md +++ b/nginx/SKILL.md @@ -408,6 +408,55 @@ cat /etc/letsencrypt/options-ssl-nginx.conf ## 八、故障排查 +### 反向代理常见错误 + +#### "URL 拼写可能存在错误" + +这个错误**不是 Nginx 本身返回的**,而是后端服务(如 Spring Boot、Node.js、Vite 等)返回的。 + +**排查步骤:** +```bash +# 第1步:直接测试后端服务(排除 Nginx 影响) +curl -v http://127.0.0.1:1234/ + +# 如果直接访问也报错 → 问题在后端,与 Nginx 无关 +# 如果直接访问正常 → 问题在 Nginx 配置 +``` + +#### proxy_pass 路径陷阱 + +```nginx +# ❌ 错误:末尾多了斜杠,会把 /app/ 替换成 / +location /app/ { + proxy_pass http://127.0.0.1:8080/; +} + +# ✅ 正确:末尾无斜杠,保持原路径 +location /app/ { + proxy_pass http://127.0.0.1:8080; # 不加 / +} + +# 特殊情况:需要去掉前缀时 +location /api/ { + # rewrite + proxy_pass 末尾斜杠 = 去掉 /api 前缀 + rewrite ^/api/(.*)$ /$1 break; + proxy_pass http://127.0.0.1:8080/; # 这里需要斜杠 +} +``` + +#### 必备的代理请求头 + +```nginx +location / { + proxy_pass http://127.0.0.1:1234; + proxy_http_version 1.1; + 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_set_header X-Forwarded-Proto $scheme; +} +``` + ### 配置测试失败 ```bash @@ -443,4 +492,25 @@ sudo certbot renew --force-renewal # 或者重新申请 sudo certbot certonly --nginx -d example.com +``` + +### 快速诊断命令 + +```bash +# 1. 检查 Nginx 和后端端口 +sudo lsof -i :1234 +sudo netstat -tlnp | grep nginx + +# 2. 直接测试后端 +curl -v http://127.0.0.1:1234/ + +# 3. 测试 Nginx 配置 +sudo nginx -t + +# 4. 查看实时日志 +sudo tail -f /var/log/nginx/access.log +sudo tail -f /var/log/nginx/error.log + +# 5. 查看完整的已加载配置 +sudo nginx -T ``` \ No newline at end of file