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

相关推荐
无敌的牛6 小时前
网络层和数据链路层
运维·服务器·网络
半梦半醒*6 小时前
ansible的playbook练习题
linux·运维·服务器·ssh·ansible·运维开发
chenfengxiu7 小时前
Centos7安装gitlab
linux·运维·gitlab
羑悻的小杀马特8 小时前
【Linux篇章】再续传输层协议UDP :从低可靠到极速传输的协议重生之路,揭秘无连接通信的二次进化密码!
linux·运维·服务器·后端·网络协议·udp
无痕melody9 小时前
飞牛nas修改crontab计划默认编辑器
运维·编辑器
Linux运维技术栈10 小时前
Linux系统部署:Certbot 实现 Nginx 自动续期&部署 Let‘s Encrypt 免费 SSL 证书
linux·运维·nginx·ssl·certbot
阿雄不会写代码10 小时前
wecross 报错这个文件找不到 tassl-1.1.1b-linux-x86_64.tar.gz
linux·运维·服务器
关关长语12 小时前
Windows 安装配置解压版Mysql8.4.5
运维·windows·mysql
孙克旭_16 小时前
day082-初识ElasticStack
linux·运维·elasticsearch