Nginx Routing Based on Headers

Nginx Routing Based on Headers

Today we meet one requirement that we need to parse and check the request header to see which server we prefer to routing to.
At first, I thought that nginx can not do that, only my lovely ha-proxy can do that.

Finally, I found that there is just lack of document to see how to do the header based routing for nginx.

I tried these configurations, it works, but I am not sure if it is the best practice.
upstream

contentcenter2 {

 ip_hash; server localhost:8201;   

}    

upstream

sillycat {        

 ip_hash;         server localhost:9000;    

}

map $http_x_header $xheader {           

 default 1;           

 "ironwolf" 2;   

}

        location / {          

proxy_pass                  http://contentcenter$xheader;    

proxy_redirect              off;           

proxy_set_header            Host $host;           

proxy_set_header            X-Real-IP $remote_addr;          

proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;          

client_max_body_size        10m;          

client_body_buffer_size     128k;          

proxy_connect_timeout       90;          

proxy_send_timeout          90;          

proxy_read_timeout          90;          

proxy_buffer_size           4k;          

proxy_buffers               4 32k;          

proxy_busy_buffers_size     64k;          

proxy_temp_file_write_size  64k;

}

So, that is it.
If we plan to visit the contentcenter1 or contentcenter2, we just need to put the X-HEADER with value ironwolf or other value.


References:
http://nginx.org/en/docs/http/ngx_http_map_module.html
http://stackoverflow.com/questions/9168377/nginx-response-based-on-the-requested-header


你可能感兴趣的:(header)