在nginx中添加和使用标头(HTTP)

时间:2012-08-15 16:17:55

标签: http nginx

我正在使用两个系统(两者都是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 / {
                proxy_pass "http://upstream0;#" is included since links are not allowed in the post
        }

   }

//备份系统

server{
        listen  777;
        server_name     _;
        #doing some other extra stuf

        #use port and protocol to direct
}

由于

2 个答案:

答案 0 :(得分:85)

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

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

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

答案 1 :(得分:8)

您可以使用上游标头(以$ 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-Upstream-01定制的X-Hdr-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
相关问题