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;
           }
        }
}
相关推荐
Web项目开发18 小时前
Dockerfile创建Almalinux9镜像
linux·运维·服务器
pride.li1 天前
开发板和Linux--nfs服务挂载
linux·运维·服务器
looking_for__1 天前
【Linux】应用层协议
linux·服务器·网络
云泽8081 天前
不止是命令:Linux 高频指令实战 + 芯片架构底层逻辑
linux·运维·服务器
j_xxx404_1 天前
Linux:基础IO
linux·运维·服务器
Trouvaille ~1 天前
【Linux】网络编程基础(二):数据封装与网络传输流程
linux·运维·服务器·网络·c++·tcp/ip·通信
万邦科技Lafite1 天前
一键获取京东商品评论信息,item_reviewAPI接口指南
java·服务器·数据库·开放api·淘宝开放平台·京东开放平台
Trouvaille ~1 天前
【Linux】网络编程基础(三):Socket编程预备知识
linux·运维·服务器·网络·c++·socket·网络字节序
德迅云安全—珍珍1 天前
低配服务器性能不够用怎么去优化?
运维·服务器
笑锝没心没肺1 天前
Linux Audit 系统配置介绍
linux·运维·服务器