如果拿到真实的用户IP地址,需要有如下前提
1、TCP 连接四元组 (src_ip,src_port,dst_ip, dst_port)
2、HTTP头部X-Forwarded-For 用户传递IP
3、HTTP头部X-Real-IP用户传递用户IP
4、网络中存在许多反向代理
X-Forwarded-For: 115.203.2.22,1.1.1.1
X-Real-IP: 115.203.2.22
拿到真实用户IP地址如何使用, nginx 是基于变量来使用的
如:binary_remote_addr、remote_addr 这样的变量,其值就是真实的IP; 这样做连接限制(limit_conn模块) 才有意义.
realip 模块,默认是不会编译进nginx 中的,可以通过如下启用功能:
--with-http_realip_module
变量:
realip_remote_addr
reaip_remote_port
指令:
set_real_ip_from
set_ip_header
real_ip_recursive
下面来演示一下
realip.conf
server {
server_name realip.zk02.com;
set_real_ip_from 192.168.27.152;
real_ip_header X-Forwarded-For;
real_ip_recursive off;
location / {
return 200 "Client real ip: $remote_addr\n";
}
}
使用include 指令加入到nginx.conf 中.
include /soft/nginx/conf/example_conf/realip.conf;
使用curl 命令验证一下
[root@zk02 conf]# curl -H 'X-Forwarded-For: 1.1.1.1,192.168.27.152' realip.zk02.com
Client real ip: 192.168.27.152
当 real_ip_recursive on; 时
[root@zk02 conf]# curl -H 'X-Forwarded-For: 1.1.1.1,192.168.27.152' realip.zk02.com
Client real ip: 1.1.1.1
[root@zk02 example_conf]# curl -H 'X-Forwarded-For: 1.1.1.1,2.2.2.2,192.168.27.152' realip.zk02.com
Client real ip: 2.2.2.2