web开发常见问题解决方案大全:502/503 Bad Gateway/Connection reset/504 timed out/400 Bad Request/401 Unauthorized/403 Forbidden
在使用反向代理(如 Nginx、HAProxy)或正向代理(如 Squid、Charles)时,经常会遇到各种 HTTP 错误码。本文将围绕以下几类常见问题,逐一分析成因并给出排查及解决思路:
代理或网关返回 HTTP 502 或 503,前端收到类似:
HTTP/1.1 502 Bad Gateway
HTTP/1.1 503 Service Unavailable
检查隧道配置
CONNECT
方法。proxy_connect
与 proxy_pass
配置,并开启 ssl_preread
(TCP 代理)或正确的 ssl
配置。查看代理日志
error_log /var/log/nginx/error.log notice;
cache.log
中查找拒绝隧道或连接错误。验证后端连通性
curl -v -x http://proxy:port https://your-upstream.example.com
重启/扩容后端
限流与熔断
客户端抛出 ECONNRESET
(Connection reset)或 ETIMEDOUT
(Connection timed out)。
日志中看到:
Error: socket hang up
Error: connect ETIMEDOUT
测试代理隧道能力
curl -v -x http://proxy:port https://example.com
CONNECT proxy:port HTTP/1.1
后就重置,说明代理不支持隧道。检查代理进程状态
ps aux
、top
观察 CPU/内存、线程数。worker_connections
、Squid 的 max_filedescriptors
)。替换或升级代理软件
网络与防火墙
前端或客户端收到:
HTTP/1.1 504 Gateway Timeout
通常表示代理等待上游响应超过设定阈值。
调整代理超时
Nginx 示例:
proxy_connect_timeout 10s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
HAProxy 示例:
timeout connect 10s
timeout server 30s
timeout client 30s
优化后端性能
异步或批处理
多活与降级
HTTP/1.1 400 Bad Request
,并提示: “代理根本不认你的 CONNECT 请求。”
确认请求格式
正确的 CONNECT 用法:
CONNECT api.example.com:443 HTTP/1.1
Host: api.example.com:443
Proxy-Authorization: Basic XXXXX
检查代理白名单
Squid 中需在配置里加:
acl SSL_ports port 443
http_access allow CONNECT SSL_ports
升级或更换代理
使用 HTTPS 直连
客户端或浏览器收到:
HTTP/1.1 401 Unauthorized
或响应头中带有 WWW-Authenticate
。
Authorization
头。检查 Authorization 头
Authorization: Bearer <token>
或 Basic <credentials>
。验证 Token 有效性
exp
、nbf
等字段。查看认证服务日志
配置 CORS
在代理或应用中允许跨域 Authorization
头:
add_header Access-Control-Allow-Headers "Authorization,Content-Type";
重试或刷新凭证
客户端收到:
HTTP/1.1 403 Forbidden
无论请求格式和认证凭证是否正确,仍提示权限不足。
检查用户角色与权限
验证访问控制配置
Nginx 示例:
location /admin {
allow 192.168.1.0/24;
deny all;
}
检查 CSRF 配置
文件/目录权限
chmod
/chown
)。日志与审计
通过以上完善的错误码排查与解决方案,基本涵盖了代理相关的常见4xx/5xx问题。从日志入手,找到根因,结合代理和后端配置,才能在复杂网络环境和高并发场景下保障服务稳定运行。