Nginx【多级代理透传真是IP】

一、使用X-Forwarded-For

  • 使用X-Forwarded-For记录真实IP,用于快速取得用户的真实IP
  • X-Real-IP 也是记录真实IP,但是他只记录上一级的IP,如果有多级代理他就不准了
一级代理192.168.200.120
二级代理192.168.200.121
web192.168.200.122

 一级代理配置

[root@nginx ~]# vim /etc/nginx/conf.d/test-01.conf 
server {
  listen 80;
  server_name www.test-01.org;
  location / {
    proxy_pass http://192.168.200.121:80;
    proxy_http_version 1.1;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}
~

二级代理配置

[root@nginx ~]# vim /etc/nginx/conf.d/test-01.conf 
server {
  listen 80;
  server_name www.test-01.org;
  location / {
    proxy_pass http://192.168.200.122:80;
    proxy_http_version 1.1;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

web配置

[root@nginx conf.d]# vim test.conf 
server {
  listen 80;
  server_name www.test-01.org;
    root /code/test;
    location / {
      index index.html;
  }
}

访问查看日志记录的IP地址

[root@nginx ~]# tailf /var/log/nginx/access.log 
192.168.200.121 - - [19/Jun/2023:19:51:33 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0" "192.168.200.10, 192.168.200.120"

二、使用realip的方式记录真实IP

  • 使用nginx Realip_module获取多级代理下的真实ip,在web节点配置
[root@nginx conf.d]# vim test.conf 

server {
  listen 80;
  server_name www.test-01.org;
    root /code/test;
    set_real_ip_from 192.168.200.120;    # 一级代理的IP地址
    set_real_ip_from 192.168.200.121;    # 二级代理的IP地址
    real_ip_header X-Forwarded-For;      # 从哪个header头检索需要的IP地址
    real_ip_recursive on;                # 排除set_real_ip_from出现的IP,剩余的就是真实IP
    location / {
      index index.html;
  }
}

[root@nginx ~]# systemctl reload nginx.service
  • 测试查看访问日志
  • 跟上面的区别就是:首IP是真实ip,那么程序员就可以通过remot_addr得到真实ip地址

[root@nginx ~]# tailf /var/log/nginx/access.log 
192.168.200.10 - - [19/Jun/2023:20:02:42 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0" "192.168.200.10, 192.168.200.120"

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦有一把琐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值