通过NGINX反向代理访问AWS API Gateway返回403 Forbidden错误
解决方案
故障根因
本次故障由ALB自动注入的X-Forwarded-Host头导致。ALB处理HTTPS请求时,会默认把客户端请求的原始域名(即xxxxxxx.example.com)写入X-Forwarded-Host头转发给后端EC2上的NGINX,当前NGINX配置没有覆盖该头,会直接透传给API Gateway前端的CloudFront服务。CloudFront校验时发现X-Forwarded-Host的值不在API Gateway默认域名的许可范围内,直接返回403,请求不会进入API Gateway服务层,因此API Gateway执行日志和WAF中都没有相关记录。
直接访问EC2上的NGINX时请求没有携带X-Forwarded-Host头,不会触发CloudFront的拦截逻辑,因此配置运行正常。
修复步骤
在NGINX配置的location块中新增一行配置,覆盖ALB注入的X-Forwarded-Host头即可,修改后的location段如下:
location / { set $upstream_endpoint xxxxxxxx.execute-api.us-east-1.amazonaws.com; resolver 169.254.169.253; proxy_set_header Host 'xxxxxxxx.execute-api.us-east-1.amazonaws.com'; # 新增以下行覆盖X-Forwarded-Host头 proxy_set_header X-Forwarded-Host 'xxxxxxxx.execute-api.us-east-1.amazonaws.com'; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2; proxy_ssl_server_name on; proxy_pass https://$upstream_endpoint; proxy_buffering off; }
修改完成后执行nginx -s reload重载配置即可恢复正常。
内容的提问来源于stack exchange,提问作者Ravindu Nirmal Fernando
相关产品推荐
相关产品推荐

