Nginx forwarding headers content loss solution

question:

When developing a gateway project, the signature sign_key information is put into the header of the request when requesting, and then taken out from the header when receiving the request. It is possible to debug locally, but after going online through the Nginx proxy, it is found that it cannot be obtained. .

原因:

By default, the nginx proxy will remove the "_" underline of the parameter in the header, so the parameter name with the "_" line cannot be obtained after the background server. You need to add this parameter in the http configuration and set it to on.

underscores_in_headers on; #该属性默认为off,表示如果header name中包含下划线,则忽略掉。

extension:

In addition, if you only need to keep some specific underline parameters in the request header, you can add the following statement to the Nginx configuration file:

ignore_invalid_headers off;

 Then in the server or location section, use the proxy_set_header directive to set the request header parameters that need to be preserved. For example:

location / {
    proxy_pass http://backend;
    proxy_set_header X-MyHeader $http_x_my_header;
}

In the above example, Nginx will keep the request header parameter named "X-MyHeader", and set its value to the value of the parameter named "x-my-header" in the original request header. 

Complete code configuration:

http {
    # 全局配置
    underscores_in_headers on;

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://backend;
            # 保留名为 X-MyHeader 的请求头参数
            proxy_set_header X-MyHeader $http_x_my_header;
        }
    }
}

In the above example, the underscores_in_headers directive is configured in the http block, ensuring that the global underscore parameters are preserved. The proxy_set_header directive is configured in the location block, retaining the request header parameter named X-MyHeader.

Guess you like

Origin blog.csdn.net/m0_37609579/article/details/129118700