nginx作反向代理实现获取客户真实ip

我们访问互联网上的服务时,大多数情况下,客户端并未直接访问到服务端,客户端的请求首先到反向代理服务器,反向代理再将请求转发到服务端实现服务访问,通过反向代理实现路由/负载均衡等策略。这样在服务端拿到的客户端IP将是反向代理IP,而不是真实客户端IP,因此需要想办法来获取到真实客户端IP

> 通常上网访问路径(比如说用阿里云主机): client(172.25.0.1) --> ADSL(拨号上网192.168.0.1) -->
> cdn(10.0.0.1) --> SLB(阿里云负载11.0.0.1) --> nginx(12.0.0.1)

模拟实现获取客户端ip

前提:一台客户机发送访问请求,一台nginx反向代理服务器转发请求,一台真实服务器

配置反向代理服务器端

????
IP为172.25.34.2

[root@base1 ~]# tar zxf nginx-1.14.2.tar.gz 
[root@base1 ~]# yum install -y gcc pcre-devel zlib-devel   # 这是编译nginx的依赖包
[root@base1 ~]# cd nginx-1.14.2
[root@base2 nginx-1.14.2]# vim auto/cc/gcc 
171 # debug
172 #CFLAGS="$CFLAGS -g" ##关闭程序bug
[root@base1 nginx-1.14.2]# make 
[root@base1 nginx-1.14.2]# ./configure --prefix=/usr/local/nginx --with-http_realip_module   # 添加了一个获取realip的模块
[root@base1 nginx-1.14.2]# make && make install

[root@base1 nginx-1.14.2]# nginx -V     # 查看编译参数

[root@base1 nginx-1.14.2]# cd /usr/local/nginx/conf/
[root@base1 conf]# vim nginx.conf
# 添加虚拟主机
     server {
         listen 80; ##监听的端口
         server_name base1.westos.org; #维护的域
 
 
         location / {
              proxy_set_header X-Real-IP $remote_addr; # 存放用户的真实ip
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   # 每经过一个反向代理,就会把反向代理IP存放在X-Forwarded-For里
        proxy_pass http://172.25.34.2:80;
    }
}
[root@base2 conf]# ln -s /usr/local/nginx/sbin/nginx /sbin
[root@base2 conf]# nginx
[root@base2 conf]# nginx -s reload

  

配置服务端

????
IP为172.25.34.3

[root@base1 conf]# vim nginx.conf
    server {
        listen 80;
        server_name base1.westos.org;   # 域名
        set_real_ip_from 172.25.34.3/24; #告知Nginx哪些是反向代理IP,即排除后剩下的就是真实客户端IP
        real_ip_header    X-Forwarded-For; #告知Nginx真实客户端IP从哪个请求头获取
        real_ip_recursive on;  ##当real_ip_recursive配置为on时,Nginx会递归解析real_ip_header指定的请求头,最后一个不匹配set_real_ip_from的IP作为真实客户端IP。 

        location / {
            root  /web;   # 指定发布目录
            index index.html index.htm;
        }
    }
[root@base1 conf]# nginx -s reload
[root@base1 conf]# mkdir /web
[root@base1 conf]# vim /web/index.html 
base1.westos.org

客户端测试

[root@foundation34 Desktop]# vim /etc/hosts
172.25.34.2  base1.westos.org
[root@found2ation34 Desktop]# curl base1.westos.org
www.westos.org

服务端查看日志

[root@base1 conf]# cat /usr/local/nginx/logs/access.log    # 通过日志可以直接查看到客户端真实ip
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值