[Linux] Nginx 反向代理配置 http headers 带下划线fields转发

Nginx 反向代理配置 http headers 带下划线fields转发

场景

应用中有个场景, web客户端提交数据时,在http header中加入某个字段. 如client_add_field.

在用ip访问时,字段可以正常获取. 改用域名访问时, 字段获取不到.

self.request.headers.get('access_token', '')

解决

Nginx在做反向代理时,一般会设置host和ip,如果你的请求的headers里有值,它是可以同时转发过去的,但是,默认情况下,并不是所有headers的fields它都会转发,fields里带有下划线(_)的,Nginx视为不合法,自动抛弃不发了。

文档:

Syntax: underscores_in_headers on | off;
Default: underscores_in_headers off;
Context: http, server

Enables or disables the use of underscores in client request header fields. When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.

想要支持下划线(_)的headers fields,需要将underscores_in_headers设置为on。

但是,如果只是设置它,会发现,并没用,因为还要设置一项:

proxy_pass_request_headers on;

    underscores_in_headers on;  // 允许headers fields 里的下划线

    location / {
        proxy_pass_request_headers on; // 确定转化http headers

        proxy_pass_header Server;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 60s;
        proxy_read_timeout 5400s;
        proxy_send_timeout 5400s;
        proxy_pass http://pb_web;
    }
原文地址:https://www.cnblogs.com/abeen/p/13873286.html