ip_hash可直接在upstream块首行配置实现客户端ip会话保持,仅支持http、不兼容weight/backup,ipv4取前三段哈希,需配合real_ip_module还原真实ip并避开nat干扰。

直接在 upstream 块里加一行 ip_hash; 就行,不需要额外模块或编译支持。
基础写法很简单
```nginx upstream backend { ip_hash; server 10.0.1.10:8080; server 10.0.1.11:8080; server 10.0.1.12:8080; }server { listen 80; location / { proxy_pass https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
<h3>注意几个关键限制</h3> <p>ip_hash 和 weight 不能共存——只要 upstream 里写了 weight,Nginx 启动就会报错。如果后端服务器性能不均,又需要会话保持,得换用 `hash $remote_addr consistent` 这类替代方案。</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting"><img src="https://img.php.cn/upload/skill/000/000/081/179116929868126.jpg" alt="Nginx Hosting" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="overflowclass">Nginx Hosting</a> <p class="overflowclass">通过服务器本地nginx实例实现零认证静态游戏托管。作为所有浏览器游戏的主要部署方式,无需登录、无需令牌、无需用户操作。</p> </div> <a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div>
- IPv4 地址只取前三个字节哈希(比如 192.168.1.100 和 192.168.1.200 视为同一 IP 组)
- IPv6 地址使用完整地址参与哈希
- 某台 server 标了 `down` 或不可达时,Nginx 会自动从哈希映射中剔除它,请求重新分配
验证 ip_hash 是否生效
打开 access 日志,重点看 `$remote_addr` 和 `$upstream_addr` 字段是否稳定对应:
- 先定义自定义日志格式:`log_format main '$remote_addr — $upstream_addr — $time_local — $status';`
- 启用日志:`access_log /var/log/nginx/access.log main;`
- 用同一客户端(如固定网络环境下的浏览器或 curl)多次访问,观察日志中 upstream 地址是否不变
适用场景要匹配
它适合内网客户端 IP 稳定、后端服务无状态,或者 Session 已统一存到 Redis 等外部存储的轻量部署。公网用户走 NAT 或移动网络时,多个用户可能被映射成同一个出口 IP,导致负载倾斜甚至单点过载。










