解決通過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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章