Nginx: use different backend based on HTTP header

Some load balancers have the ability to select different virtual server pools based on client http headers. This can be really convenient for staging and development work since you can use the same url across all instances. I wanted to do this on Nginx but had problems finding anyone that had done it before.

To accomplish this in Nginx you can use the following code in your configuration.

For example, if you set the “X-Server-Select” header in your browser to “staging” you get the staging server. You may want to create a visual identifier on the page to tell you what upstream server you are connecting to. Some useful plugins for setting client HTTP headers in the browser are: