You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx未将AWS API Gateway ID传递至EC2请求头User-Agent问题求解

可行配置方案

实现逻辑

AWS API Gateway向EC2转发请求时,默认会携带X-Amzn-Apigateway-Api-Id请求头,值为对应API Gateway的ID。我们只需要在Nginx中将原User-Agent头与该ID按照要求的格式拼接,再传递给上游业务代码即可。

完整修改后的Nginx配置

#Modifed Elastic Beanstalk Nginx Configuration File
user                    nginx;
error_log               /var/log/nginx/error.log warn;
pid                     /var/run/nginx.pid;
worker_processes        auto;
worker_rlimit_nofile    66966;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '$status $body_bytes_sent "$http_referer" ';
                     
    include       conf.d/*.conf;
    map $http_upgrade $connection_upgrade {
        default     "upgrade";
    }
    # 新增map块:判断是否存在API Gateway ID,生成修改后的User-Agent
    map $http_x_amzn_apigateway_api_id $modified_user_agent {
        # 没有API Gateway ID时,保留原始User-Agent
        default $http_user_agent;
        # 存在API Gateway ID时,按照要求格式拼接
        ~^.+$ "$http_user_agent, AmazonAPIGateway_$http_x_amzn_apigateway_api_id";
    }
    server {
        listen        80 default_server;
        access_log    /var/log/nginx/access.log main;
        client_header_timeout 60;
        client_body_timeout   60;
        keepalive_timeout     60;
        gzip                  off;
        gzip_comp_level       4;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
        # 新增配置:将修改后的User-Agent传递给上游业务服务
        proxy_set_header User-Agent $modified_user_agent;
        # Include the Elastic Beanstalk generated locations
        include conf.d/elasticbeanstalk/*.conf;
    }
}

生效验证

  1. 执行nginx -t命令检查配置语法是否正确,确认返回syntax is ok和test is successful
  2. 执行nginx -s reload重载Nginx配置使修改生效
  3. 从APP端发起测试请求,验证业务服务收到的User-Agent是否符合预期格式

内容的提问来源于stack exchange,提问作者Rizwan Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:54:04