带请求体的GET请求经Nginx代理失败问题求助
问题
我在AWS API Gateway中配置了一个支持携带JSON请求体的GET端点,直接调用该端点可正常返回200响应,调用命令如下:
curl -X GET \ -d '{"pageSize":"10", "pageNumber":"1", "id": "xyz"}' \ "https://abcd.us-east-1.amazonaws.com/xyz/audit/list"
但通过Nginx代理调用该端点时,返回如下4xx错误页面:
<html> <head> <title> ERROR accessing content </title> </head> <body> <h1 color='red'>HTTP Error 4xx: Content is not available</h1> </body> </html>
推测Nginx配置无法正确识别带请求体的GET请求,当前Nginx配置如下:
server { listen 443 ssl proxy_protocol; location /xyz/audit/list { proxy_pass https://abcd.us-east-1.amazonaws.com/xyz/audit/list; proxy_set_header X-Forwarded-For $proxy_protocol_addr; proxy_pass_request_headers on; proxy_method GET; add_header X-Body $request_body; add_header X-Frame-Options DENY; add_header 'Cache-Control' 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0'; add_header 'Pragma' 'no-cache'; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Content-Security-Policy "frame-ancestors 'self'"; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; expires off; } }
使用该配置调用带请求体的GET请求失败,但带JSON体的POST请求可正常工作。请问我缺少了哪些配置参数?
解决方案
问题核心是Nginx默认不会主动处理并转发GET请求的请求体,需要添加以下关键配置:
proxy_pass_request_body on;:明确指定Nginx将客户端的请求体转发到后端服务器,GET请求默认不会开启这个行为,而POST请求默认是启用的,这也是POST能正常工作的原因。client_body_in_single_buffer on;(可选但推荐):将请求体完整存入单个内存缓冲区,避免因请求体分段导致转发不完整,确保JSON格式的请求体被完整传递到AWS API Gateway。
修改后的location配置如下:
location /xyz/audit/list { proxy_pass https://abcd.us-east-1.amazonaws.com/xyz/audit/list; proxy_set_header X-Forwarded-For $proxy_protocol_addr; proxy_pass_request_headers on; # 新增的关键配置 proxy_pass_request_body on; client_body_in_single_buffer on; proxy_method GET; add_header X-Body $request_body; add_header X-Frame-Options DENY; add_header 'Cache-Control' 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0'; add_header 'Pragma' 'no-cache'; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Content-Security-Policy "frame-ancestors 'self'"; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; expires off; }
注:虽然HTTP规范允许GET请求携带请求体,但并非所有服务端都支持该用法,不过你的AWS API Gateway已配置支持,只需确保Nginx完成正确转发即可。
内容的提问来源于stack exchange,提问作者Rohit
相关产品推荐
相关产品推荐

