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协议

相关推荐
萧曵 丶7 分钟前
Nginx 高频面试题(含答案)
运维·nginx
吕司19 分钟前
Linux系统安装MySQL
linux·运维·服务器
犀思云21 分钟前
构建全球化多云网格:FusionWAN NaaS 在高可用基础设施中的工程实践
运维·网络·人工智能·系统架构·机器人
无名的小白1 小时前
openclaw使用nginx反代部署过程 与disconnected (1008): pairing required解决
java·前端·nginx
yuankoudaodaokou2 小时前
革新自动化产线调试,扫描生成点云精准引导机器人路径
运维·python·机器人·自动化
wengad2 小时前
podman搭建nginx服务
运维·nginx·podman
阡陌..2 小时前
Linux下的vi和vim使用方法
linux·运维·vim
hweiyu002 小时前
Linux 命令:diff
linux·运维·服务器
进击切图仔2 小时前
基于 linux 20.04 构建 ros1 noetic 开发环境 -离线版本
linux·运维·服务器
晚风吹长发2 小时前
初步了解Linux中的线程同步问题及线程安全和死锁与生产消费者模型
linux·运维·服务器·开发语言·数据结构·安全