2012-08-15 37 views
19

我使用兩個系統(都是nginx負載均衡器,一個用作備份)。我想添加和使用很少的http自定義標題。請給你的建議在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 
} 

感謝

回答

51

要添加頁眉只是將下面的代碼添加到您要添加的位置塊標題:

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

顯然,將x-my-header和my-header-content替換爲你想添加的內容。這就是它的全部。

+0

謝謝。我如何在另一位聽衆中讀取它? – mohan 2012-08-15 17:28:38

+2

$ http_HEADER和$ send_http_HEADER變量允許訪問nginx中標題的內容請參閱http://wiki.nginx.org/HttpCoreModule#Variables – cobaco 2012-08-15 17:42:09

+0

當使用'proxy_pass'時'add_header'是否工作?這個問題似乎與它相矛盾:http://stackoverflow.com/questions/14501047/how-to-add-a-response-header-on-nginx-when-using-proxy-pass – 2016-03-21 15:46:39

5

您可以使用上游標頭(以$ 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,由服務器seted和X-上游-01,seted客戶:

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 
相關問題