Thursday, May 7, 2020

Use different backend based on HTTP Header in Nginx

To do this, you can use this configuration:


upstream production {
     server 10.0.0.1:80;
}

upstream stage {
     server 10.0.0.2:80;
}


# map to different upstream backends based on header
map $http_x_which_deployment $pool {
     default "production";
     stage "stage";
}

server {
     listen 80;
     server_name _;
     location / {
            proxy_pass http://$pool;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $http_true_client_ip;
            proxy_set_header Host $host;
            proxy_connect_timeout       600;
            proxy_send_timeout          600;
            proxy_read_timeout          600;
            send_timeout                600;     }
}



Then if you add "X-Which-Deployment" header and set it to "stage", you will be pointed to "Stage Server" (here 10.0.0.2).

No comments: