Nginx select based on HTTP header
Feb 27, 2018There is a service api.example
with two different versions:
- 1.0.0:
api-v1.example
- 2.0.0:
api-v2.example
To select different virtual server pools based on client http headers, such as:
# To api-v1.example
$ curl -X GET \
-H 'Version: 1.0.0' \
http://api.example
# To api-v2.example
$ curl -X GET \
-H 'Version: 2.0.0' \
http://api.example
# To api-v2.example by default
$ curl -X GET \
http://api.example
To accomplish this in Nginx you can use the following code in your configuration:
upstream v1 {
server api-v1.example;
}
upstream v2 {
server api-v2.example;
}
# map to different upstream backends based on header
map $http_api_version $pool {
default "v2";
1.0.0 "v1";
2.0.0 "v2";
}
server {
listen 80;
server_name api.example;
location / {
proxy_pass http://$pool;
#standard proxy settings
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
Also looking for here.