【问题标题】:Adding and using header (HTTP) in nginx [closed]在 nginx 中添加和使用标头(HTTP)[关闭]
【发布时间】:2012-08-11 23:15:48
【问题描述】:

我正在使用两个系统(两个都是 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
}

我怎样才能做到这一点?

【问题讨论】:

    标签: http nginx


    【解决方案1】:

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

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

    显然,将 x-my-header 和 my-header-content 替换为您要添加的内容。仅此而已。

    【讨论】:

    • $http_HEADER 和 $send_http_HEADER 变量允许访问 nginx 中的标头内容,请参阅wiki.nginx.org/HttpCoreModule#Variables
    • 当使用proxy_passadd_header 工作吗?这个问题似乎与它相矛盾:stackoverflow.com/questions/14501047/…
    • @cobaco 此配置将此标头添加到响应标头中。有没有办法在将请求头发送到代理服务器时添加它?
    • @IndraUprade 发送到后端代理服务器的标头由 proxy_set_header 管理:nginx.org/en/docs/http/…
    • 还要在末尾添加 always 以使其适用于 400 个代码
    【解决方案2】:

    您可以使用上游标头(以 $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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2014-08-21
      • 1970-01-01
      • 2018-04-05
      相关资源
      最近更新 更多