使用 map ,测试了一下没问题
```
# 根据请求头 environment_name 映射目标地址
map $http_environment_name $backend {
default http://127.0.0.1:8022/api/; # 默认地址
loc http://127.0.0.1:28080; # loc 的地址
pro http://127.0.0.1:8011/api/; # pro 的地址
}
server {
listen 80;
location /aa {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
# 动态选择后端
proxy_pass $backend;
}
}
```
```
~ » cat
test_njet.sh 130 ↵ xtcc@xtcc-b560m-power
curl -H "environment-name: " http://127.0.0.1:8089/aa
curl -H "environment-name: ssss" http://127.0.0.1:8089/aa
curl -H "environment-name: loc" http://127.0.0.1:8089/aa
curl -H "environment-name: pro" http://127.0.0.1:8089/aa
```
```
2025/01/13 17:02:01 [error] 238783#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /aa HTTP/1.1", upstream: "http://127.0.0.1:8022/api/", host: "127.0.0.1:8089"
2025/01/13 17:02:01 [error] 238784#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /aa HTTP/1.1", upstream: "http://127.0.0.1:8022/api/", host: "127.0.0.1:8089"
2025/01/13 17:02:01 [error] 238785#0: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /aa HTTP/1.1", upstream: "http://127.0.0.1:28080/aa", host: "127.0.0.1:8089"
2025/01/13 17:02:01 [error] 238786#0: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /aa HTTP/1.1", upstream: "http://127.0.0.1:8011/api/", host: "127.0.0.1:8089"
```
顺便推广一下我们的 njet:
https://gitee.com/njet-rd/njet