如果拿到真實的用戶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