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;
           }
        }
}
相关推荐
终端行者5 分钟前
Nginx 配置Websocket代理 Nginx 代理 Websocket
运维·websocket·nginx
是小胡嘛43 分钟前
华为云CentOS系统中运行http服务器无响应
linux·服务器·c++·http·centos·华为云
小猪佩奇TONY1 小时前
OpenGL-ES 学习(16) ----Pixel Buffer Object
服务器·学习·elasticsearch
Mr.H01271 小时前
(上册)TCP 服务器核心流程实操指南
linux·服务器·网络·tcp/ip
HappRobot1 小时前
WebLogic服务器的JVM参数调整
服务器·jvm·chrome
饭九钦vlog2 小时前
修复重装机kali机器上不了网络域名问题一键脚本
服务器·网络·php
Caster_Z3 小时前
WinServer安装NPM(Nginx Proxy Manager),并设置反向代理和开启https
前端·nginx·npm
TG:@yunlaoda360 云老大3 小时前
怎么在亚马逊云服务器上部署Node.js?
运维·服务器·node.js·aws
拾忆,想起4 小时前
Dubbo跨机房调用实战:从原理到架构的完美解决方案
服务器·网络·网络协议·tcp/ip·架构·dubbo
NiKo_W5 小时前
Linux 数据链路层
linux·服务器·网络·内网穿透·nat·数据链路层