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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM