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;
           }
        }
}
相关推荐
小二李2 小时前
第11章 nestjs服务端开发:登录鉴权
运维·服务器
i建模3 小时前
如何在Arch Linux中重设忘记的root密码
linux·运维·服务器
何中应6 小时前
vmware的linux虚拟机如何设置以命令行方式启动
linux·运维·服务器
野犬寒鸦6 小时前
从零起步学习并发编程 || 第一章:初步认识进程与线程
java·服务器·后端·学习
百炼成神 LV@菜哥6 小时前
Kylin Linux V10 aarch64 安装启动 TigerVNC-Server
linux·服务器·kylin
m0_737302586 小时前
百度智能云边缘云服务器,端云协同赋能全域智能场景
服务器
Anastasiozzzz7 小时前
LeetCode Hot100 295. 数据流的中位数 MedianFinder
java·服务器·前端
Exquisite.7 小时前
Nginx
服务器·前端·nginx
j_xxx404_7 小时前
Linux:进程程序替换
linux·运维·服务器
祁鱼鱼鱼鱼鱼7 小时前
Keepalived实验环境设定
linux·服务器·网络