nginx-realip问题解决方案

nginx-realip问题解决方案


一、配置真实ip解析

让backend server知道前端是谁来访问的,知道他们的ip地址

LB在转发数据包的时候,在http请求报文里增加一个字段,携带user的ip地址,这样backend server就知道user的ip地址了

在负载均衡器上修改http请求报文头部字段,添加一个X-Real-IP字段

配置在监听80端口的server 虚拟主机上,到时访问的时候使用http协议访问

bash 复制代码
[root@LB conf]# vim nginx.conf
 server {
        listen       80;
        location / {
        # 转发给负载均衡器
         proxy_pass  http://myweb1;
         proxy_set_header  X-Real-IP  $remote_addr;
        }

[root@LB conf]# nginx  -t
nginx: the configuration file /usr/local/nginx1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1/conf/nginx.conf test is successful
[root@LB conf]# nginx  -s reload

将nginx内部的remote_addr这个变量的值,赋值给X-Real-IP这个变量,X-Real-IP这个变量会在http协议的请求报文里添加一个X-Real-IP的字段,后端的real server 服务器上的nginx就可以读取这个字段的值 X-Real-IP

这个变量名可以自己定义,随便取名,后面引用的时候,不区分大小写


二、日志中记录真实 IP

在后端real server上使用这个x_real_ip这个字段

web1和web2服务器上都要进行修改

bash 复制代码
[root@web-1 conf]# vim nginx.conf
http {
    include       mime.types;
    include       /usr/local/nginx1/conf/conf.d/*.conf;
    server_tokens off;
   #在日志文件的格式里,增加变量$http_x_real_ip  表示我们引用这个变量的值写到日志文件里
    log_format  main  '$http_x_real_ip  - $remote_addr -  $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
   #启用下main格式的访问日志
  access_log  logs/access.log  main;
  server {
        listen 80;
        server_name www.huang.com;
        access_log  logs/huang.com.access.log  main;
.......省略

[root@web-1 conf]# nginx  -t
nginx: the configuration file /usr/local/nginx1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1/conf/nginx.conf test is successful
[root@web-1 conf]# nginx  -s reload

三、在日志中验证

测试 -> 访问LB

效果就是在日志文件里能看到前端用户的ip地址,具体看哪个日志文件,需要在web服务器上确认访问的是哪个虚拟主机,然后确认是哪个access.log文件,就能看到real ip的地址

root@web2 logs\]# tail -f huang.com.access.log ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/968b0644bcec4866a4bc8964cf2e3d68.png) 配置在监听443端口的server 虚拟主机里,访问的时候使用https协议

相关推荐
芝麻开门-新起点17 小时前
数据脱敏与自动化技术融合:大规模GIS数据安全高效处理方案
运维·自动化
行走正道17 小时前
【探索实战】跨云应用分发自动化实战:基于Kurator的统一交付体系深度解析
运维·自动化·wpf·kurator·跨云分发
杨云龙UP18 小时前
SQL Server 备份异地同步 + 清理脚本
运维·服务器·数据库·sql·mysql·sqlserver
q***484119 小时前
Nginx中$http_host、$host、$proxy_host的区别
运维·nginx·http
_lst_20 小时前
linux进程状态
linux·运维·服务器
k***121720 小时前
【Nginx 】Nginx 部署前端 vue 项目
前端·vue.js·nginx
霍格沃兹测试开发学社-小明20 小时前
AI来袭:自动化测试在智能实战中的华丽转身
运维·人工智能·python·测试工具·开源
MaisieKim_20 小时前
2025年企业文档管理系统全面评测报告
运维·数据库
zzzsde21 小时前
【Linux】基础开发工具(3):编译器
linux·运维·服务器
..空空的人1 天前
C++基于websocket的多用户网页五子棋 ---- 整合封装服务器模块设计实现
运维·服务器