Nginx负载均衡时如何为指定ip配置固定服务器

大家在用Nginx做负载均衡时,一般是采用默认的weight权重指定或默认的平均分配实现后端服务器的路由,还有一种做法是通过ip_hash来自动计算进行后端服务器的路由,但最近遇到一个问题,就是希望大部分用户采用ip_hash自动分配后端服务器的同时,如何将指定ip或ip段访问指向指定后端服务器?本文主要利用Nginx的upstream模块的ip_hash实现负载均衡,同时结合geo模块,通过ip_hash、default来实现上述需求,具体配置情况如下,供大家参考,记得重启nginx,即可实现配置调整。配置完成后,ip为10.45.217.0/24段的用户在访问http://10.40.129.100:3001时,将自动路由到http://10.40.129.61:3000

复制代码
# 本机ip:10.40.129.100,以下是nginx.conf配置文件。
http {
	include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
	                  '$status $body_bytes_sent "$http_referer" '
	                  '"$http_user_agent" "$http_x_forwarded_for"';
	access_log  logs/access.log  main;

	geo $back_servers {
	    default backend;  # 默认后端
	    10.45.217.0/24 backend2;  # 指定 IP 段对应的后端服务器(10.40.129.61) 客户端的C段:相当于10.45.217.0至10.45.217.255之间的所有ip。
	}

    upstream backend {
        ip_hash;
        server 10.40.129.61:3000;  
        server 10.40.129.90:3000;  
    }
	upstream backend2 {
	    server 10.40.129.61:3000;  
	}

        # 1.HTTP Server
        server {
           listen       3001;    
           location / {             
				client_max_body_size  100m;
            	proxy_set_header Host $host:3000;
            	proxy_set_header X-Real-IP $remote_addr;
            	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            	proxy_set_header X-Forwarded-Proto $scheme;	
				proxy_set_header   Connection   ""; 
				proxy_pass http://$back_servers;
           }
        }
}
相关推荐
the_nov9 分钟前
19.TCP相关实验
linux·服务器·网络·c++·tcp/ip
Y淑滢潇潇1 小时前
RHCSA Linux 系统创建文件
linux·运维·服务器
XYN611 小时前
【嵌入式学习3】基于python的tcp客户端、服务器
服务器·开发语言·网络·笔记·python·学习·tcp/ip
the_nov1 小时前
20.IP协议
linux·服务器·网络·c++·tcp/ip
源代码•宸2 小时前
Visual Studio Code SSH 连接超时对策( keep SSH alive)
运维·服务器·ide·经验分享·vscode·ssh
zyx没烦恼3 小时前
Linux 下 日志系统搭建全攻略
linux·服务器·开发语言·c++
大橘3 小时前
centos8上实现lvs集群负载均衡dr模式
服务器·负载均衡·lvs
半新半旧4 小时前
Nginx 负载均衡案例配置
运维·nginx·负载均衡
码上飞扬4 小时前
深入探索 Linux Top 命令:15 个实用示例
linux·运维·服务器
灰色人生qwer4 小时前
内网服务器centos7安装jdk17
java·运维·服务器