proxy_set_header的使用

在Nginx中,proxy_set_header可以让我们对请求中的头部进行重定义、或者是增加请求头,再一并发送给被代理的服务器。

比如:

1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name localhost;

location / {
proxy_set_header Host $host;
proxy_pass http://your_service;
}
}

我们通过proxy_set_header Host $host,将真正请求的Host设置到头部,给到被代理的服务。

注意

proxy_set_header可以被使用在http,server,location这几个上下文中。

这里其实有一个可能会被忽略的注意点,对于nginx的文档描述是这样的:

These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level

说的是:当且仅当当前level没有proxy_set_header的配置,才继承上层的配置。

单独提到这个注意事项是因为,有时候我们可能会将几个location的通用配置提到server中,然后在某一个location里面,我们为这个location单独做了一些配置。

这个时候,很容易忽略了我们在server中配置的通用header,导致header传给被代理服务器的时候少了。

比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

server {
listen 80;
server_name localhost;

proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

location / {
proxy_pass http://your_service;
}

location /other {
rewrite /other/(.*) /$1 break;
proxy_set_header Test test;
proxy_pass http://your_service/test;
}
}

当我们这么配置的时候,问题就来了,因为我们在location /other里面,使用了proxy_set_header
这个时候在server层配置的Host、X-Forwarded-For等等,都不会传给被代理服务器,
原因就是上面提到的那点:当且仅当当前level没有proxy_set_header的配置,才继承上层的配置