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

moh*_*han 42 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 / {
        # is included since links are not allowed in the post
        proxy_pass "http://upstream0;"
    }
}
Run Code Online (Sandbox Code Playgroud)

//备份系统

server {
    listen 777;
    server_name _;
    #doing some other extra stuff
    #use port and protocol to direct
}
Run Code Online (Sandbox Code Playgroud)

谢谢

cob*_*aco 101

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

location some-location {
  add_header X-my-header my-header-content;      
}
Run Code Online (Sandbox Code Playgroud)

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

  • 发送到后端代理服务器的@IndraUprade标头通过proxy_set_header进行管理:http://nginx.org/zh-CN/docs/http/ngx_http_proxy_module.html#proxy_set_header (3认同)
  • $ http_HEADER和$ send_http_HEADER变量允许访问nginx中头文件的内容,请参阅http://wiki.nginx.org/HttpCoreModule#Variables (2认同)
  • 使用“proxy_pass”时“add_header”是否有效?这个问题似乎与之相矛盾:http://stackoverflow.com/questions/14501047/how-to-add-a-response-header-on-nginx-when-using-proxy-pass (2认同)
  • 还要在末尾添加“always”以使其适用于 400 个代码 (2认同)

shc*_*bak 8

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

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;
Run Code Online (Sandbox Code Playgroud)

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

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
Run Code Online (Sandbox Code Playgroud)

响应包含由服务器和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
Run Code Online (Sandbox Code Playgroud)