Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and using header (HTTP) in nginx [closed]

Tags:

http

nginx

I am using two system (both are Nginx load balancer and one act as backup).

I want to add and use few HTTP custom headers.

Below are my codes for both;

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;"     } } 

Backup system

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

How can I achieve that?

like image 366
mohan Avatar asked Aug 15 '12 16:08

mohan


People also ask

What is add header in nginx?

What is the Nginx add_header directive? # The Nginx add_header directive allows you to define an arbitrary response header and value to be included in all response codes, which are equal to 200 , 201 , 204 , 206 , 301 , 302 , 303 , 304 , or 307 . This can be defined from within your nginx.

How do I add a header to an HTTP response?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.


2 Answers

To add a header just add the following code to the location block where you want to add the header:

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

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

like image 178
cobaco Avatar answered Oct 06 '22 01:10

cobaco


You can use upstream headers (named starting with $http_) and additional custom headers. For example:

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

next, go to console and make request with user's header:

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

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

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 
like image 44
shcherbak Avatar answered Oct 05 '22 23:10

shcherbak