解决通过Nginx转发的服务请求头header中含有下划线的key,其值取不到的问题

1. 问题

由于在http请求头的头部中设置了一些自定义字段,刚好这些字段中含有下划线,比如bundle_name这种,后端在进去获取头部信息时,发现取不到对应的值

2. 原因及解决办法

分析

首先看一段nginx源码

ngx_http_parse_header_line(ngx_http_request_t *r, ngx_buf_t *b,ngx_uint_t allow_underscores)

if (ch == '_') {
    if (allow_underscores) {
        hash = ngx_hash(0, ch);
        r->lowcase_header[0] = ch;
        i = 1;
    } else {
        r->invalid_header = 1;
    }
     break;
}

这里有一个关键变量:allow_underscores,是否允许下划线。

原来nginx对header name的字符做了限制,默认 underscores_in_headers 为off,表示如果header name中包含下划线,则忽略掉。而我的自定义header中恰巧有下划线变量。

解决办法

方法一:

header中自定义变量名时不要用下划线

方法二:

在nginx.conf中加上underscores_in_headers on配置

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    underscores_in_headers on;
    keepalive_timeout  65;
}

参考:
https://blog.csdn.net/loongshawn/article/details/78199977

原文地址:https://www.cnblogs.com/huchong/p/10246031.html