Search code examples
nginxnginx-reverse-proxynginx-config

Nginx | How to configure based on urls & header


Basically i have 2 rules already based on url pattern. Now i would like add another condition based on header value, let say the if source header = "gif" then redirect the request to this upstream "http://zone3.svc.cluster.local:4911;", if the source present but the value is different, if source is not even present then proceed with url based conditions i have below and redirect the request. How can achieve this using nginx ? Nginx version: v1.14.2

location ~ ^/v[1-9]+(.[0-9]+)*/abc/fetch {
set $upstream http://zone1.svc.cluster.local:4911;
proxy_pass $upstream;
}

location ~ ^/v[1-9]+(.[0-9]+)*/abc/b2c {
set $upstream http://zone2.svc.cluster.local:4911;
proxy_pass $upstream;
}

// fallback rule
location ~ ^/v[1-9]+(.[0-9]+)*/abc {
set $upstream http://zone.svc.cluster.local:4911;
proxy_pass $upstream;
}

There is also buzz around not use if, as if being evil in nginx. What way is better.


Solution

  • This should work. I got this from nginxcommunity slack. Person Name: Liam.

    map $http_source $final_upstream {
       "gif" http://zone3.svc.cluster.local:4911;
       "png" http://zone3.svc.cluster.local:4912;
        default $upstream;
    }
    
    server {
        location ~ ^/v[1-9]+(.[0-9]+)*/abc/fetch {
            set $upstream http://zone1.svc.cluster.local:4911;
            proxy_pass $final_upstream; # Evaluated by map block
        }
        #...
    }