65

我正在使用两个系统(都是 Nginx 负载均衡器,一个充当备份)。

我想添加和使用一些 HTTP 自定义标头。

以下是我的代码;

upstream upstream0 {
    #list of upstream servers
    server backend:80;
    server backup_load_balancer:777 backup;
    #healthcheck
}

server {
    listen 80;
    #Add custom header about the port and protocol  (http or https)
    server_name _;

    location / {
        # is included since links are not allowed in the post
        proxy_pass "http://upstream0;"
    }
}

备份系统

server {
    listen 777;
    server_name _;
    #doing some other extra stuff
    #use port and protocol to direct
}

我怎样才能做到这一点?

4

2 回答 2

143

要添加标头,只需将以下代码添加到要添加标头的位置块:

location some-location {
  add_header X-my-header my-header-content;      
}

显然,将 x-my-header 和 my-header-content 替换为您要添加的内容。这就是它的全部。

于 2012-08-15T17:10:46.883 回答
12

您可以使用上游标头(以 $http_ 开头)和其他自定义标头。例如:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

接下来,转到控制台并使用用户的标头发出请求:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

响应包含由服务器设置的 X-Hdr-01 和由客户端设置的 X-Upstream-01:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
于 2015-12-01T00:01:45.883 回答