Routing traffic in nginx according to received header

Nadav Aviv asked:

I’m trying to route traffic in my nginx proxy according to a received header.

My infrastructure is built in a way that traffic is being sent to the proxy with a header that contains part of the address that I want to route to.

Here is my code:

upstream target {
    server $ max_fails=3 fail_timeout=60;

server {
    listen 80 default_server;
    location / {
        proxy_pass http://target;
        proxy_redirect off;
        proxy_http_version 1.1;

Unfortunately I’m getting the following error when starting nginx:

host not found in upstream "$"

Is there any way I can dynamically edit the server’s target url according to a given header?


My answer:

An upstream server doesn’t accept variables, but you can use it in proxy_pass directly. (And it doesn’t really make that much sense to define an upstream with only one server.) For example:

    proxy_pass http://$; 

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.