我有两个后端服务器在 192.168.0.101:8080 和 192.168.0.102:8080 上运行。
我在 192.168.0.111:80 上运行 nginx,我想强制 nginx 通过 IP 在特定的后端服务器中反转流量。
geo $upstream {
192.168.0.150 backend-1;
192.168.0.250 backend-2;
default backend-1;
}
upstream backend-1 {
ip_hash;
server 192.168.0.101:8080;
}
upstream backend-2 {
ip_hash;
server 192.168.0.102:8080;
}
server {
listen 80;
location / {
proxy_pass http://$upstream;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
我对这个配置感到困惑。它会按预期工作吗?除了 192.168.0.150 之外的每个请求都会转到后端 1(192.168.0.102:8080) 吗?192.168.0.250 会转到后端 2 吗?
问题:它没有根据 IP 地址进行重定向。这是为什么?
答案1
工作配置:
geo $upstream {
default backend-1;
192.168.0.150 backend-1;
192.168.0.250 backend-2;
}
upstream backend-1 {
server 192.168.0.101:8080;
}
upstream backend-2 {
server 192.168.0.102:8080;
}
server {
listen 80;
location / {
proxy_pass http://$upstream;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}