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

相关推荐
晓梦初醒p3 小时前
finalshell 连接服务器报错channel is not opened
linux·运维·服务器
准时准点睡觉3 小时前
HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容——错误代码:0x00000000
运维·服务器·iis·asp.net
cpsvps3 小时前
环境变量管理于美国服务器多环境部署的实施标准
运维·服务器·数据库
IvorySQL3 小时前
【生态再升级】IvorySQL 4.5 与银河麒麟高级服务器操作系统V11完成适配认证!
运维·服务器·数据库·postgresql·ivorysql
段振轩3 小时前
Docker nginx容器部署前端项目。
前端·nginx·docker
网硕互联的小客服3 小时前
服务器密码错误被锁定如何解决?
运维·服务器·网络·安全
2301_767902643 小时前
NFS 服务器&&iSCSI 服务器
运维·服务器·php
云游3 小时前
Zabbix7.4.8(一):通过Zabbix agent 2监控postgresql相关指标
运维·postgresql·zabbix
你什么冠军?3 小时前
linux入门4.5(NFS服务器和iSCSI服务器)
linux·运维·服务器
Kaede63 小时前
如何快速排查服务器宕机故障
运维·服务器