nginx转发请求丢失自定义请求头

问题:使用nginx代理请求时,请求头丢失,导致后端无法获取到请求头。

原配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
location /mp/ {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header mp_token $http_mp_token;

proxy_buffering off;
proxy_cache off;

send_timeout 600;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
}

先说解决方式,nginx.conf配置文件中http配置块下增加underscores_in_headers on;,因为默认情况下,nginx的配置负载均衡器会删除掉带下划线的请求头

1
2
3
4
5
http {
include mime.types;
default_type application/octet-stream;
# 增加这个配置
underscores_in_headers on;

nginx官方文档说明

  • 原文说明如下
1
2
3
First, the load balancer will drop any empty headers it gets. 
Headers with underscores are dropped as well.
If your upstream web servers are relying on headers that have underscores in them, they’re not going to get them unless you configure your load balancer with the underscores_in_headers directive to make that available.

翻译

1
2
首先,负载均衡器将删除它获得的所有空标头。带有下划线的标题也会被删除。
如果您的上游 Web 服务器依赖于其中包含下划线的标头,则除非您使用underscores_in_headers指令配置负载均衡器以使其可用,否则它们将无法获取它们。