5

nginx做转发时,带下划线字段的header内容丢失

 2 years ago
source link: https://www.jianshu.com/p/4c2983f1a441
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

nginx做转发时,带下划线字段的header内容丢失

2021.06.10 11:09:57字数 255阅读 28

在日常的开发中,我们有时候会在http请求头中设置一些自定义的字段,比如这种格式x_token, x_ticket, x_uid, x_version,app_id等,这些字段中都含有下划线。 但后端程序获取头部信息时,会取不到对应的值。

场景复现x_test 去哪儿了?

www@SD-20200928IIIF:~$ curl --location --request GET 'http://localhost/test/header/get-header.php' \
> --header 'x_test: xxxxx' \
> --header 'y-test: yyyyy'
{
    "post": [],
    "header": {
        "y-test": "yyyyy",
        "user-agent": "curl\/7.68.0"
    }
}

其实nginx对header name的字符做了限制,默认 underscores_in_headers 为off。

当是off的时候,忽略在客户端请求头字段中设置的下划线参数。名称包含下划线的请求标头字段将被标记为无效,并受ignore_invalid_headers指令的约束 。

之所以为off,其实官方也是不推荐采用下划线方式的。

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

个人比较推荐这种方式。常见的header变量都是遵循这种方式,例如:Content-Type,Content-Length,Accept-Ranges等。

在nginx.conf中加上underscores_in_headers on配置

http {
    ...
    underscores_in_headers on;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK