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

Nginx反向代理自定义location配置下无法传递header头值如何解决

问题解决方案

核心原因:Nginx 默认配置下underscores_in_headers参数为off,会自动丢弃名称中包含下划线的请求头,你用到的access_token header包含下划线,所以被Nginx默认过滤,无法传递到后端服务。

你可以选择以下任意一种方案解决:

方案1:调整Nginx配置允许带下划线的header(最快修复)

在Nginx的server块或者当前的location @rest_api块添加underscores_in_headers on配置即可,修改后的@rest_api配置参考:

location @rest_api {
    # 允许带下划线的header传递
    underscores_in_headers on;
    proxy_http_version 1.1;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header HOST $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_cache_bypass $http_upgrade;
    # 可额外显式指定传递access_token,双重保险
    proxy_set_header access_token $http_access_token;
    proxy_pass http://api:7000;
}

修改完成后重启Nginx容器即可生效。

方案2:修改header命名为横杠分隔(符合HTTP规范,推荐长期使用)

HTTP header 通用规范约定命名使用横杠分隔而非下划线,你可以将前端传递的access_token改为access-token,后端Nest代码对应改为读取access-token header即可,不需要修改Nginx配置,兼容性更好。

额外CORS配置校验

如果你的请求是跨域请求,需要确认Nest的CORS配置放行自定义header,避免浏览器拦截,可将Nest启动代码调整为:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { 
    cors: {
      origin: true,
      // 放行你用到的自定义header
      allowedHeaders: ['access_token', 'access-token', 'Content-Type', 'Authorization'],
      exposedHeaders: ['access_token', 'access-token']
    } 
  });
  app.setGlobalPrefix('api');
  await app.listen(7000);
}
bootstrap();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:21:03