随着nginx的迅速崛起,越来越多公司将apache更换成nginx. 同时也越来越多人使用nginx作为负载均衡, 并且代理前面可能还加上了CDN加速,但是随之也遇到一个问题:nginx如何获取用户的真实IP地址.
实例环境:
假如说你的CDN厂商使用nginx,那么在nginx上将$remote_addr赋值给你指定的头,方法如下:
proxy_set_header remote-user-ip $remote_addr;
后端PHP代码getRemoteUserIP.php
<?php
$ip = getenv("HTTP_REMOTE_USER_IP");
echo $ip;
?>
访问getRemoteUserIP.php,结果如下:
120.22.11.11 //取到了真实的用户IP,如果CDN能给定义这个头的话,那这个方法最佳
一般情况下CDN服务器都会传送HTTP_X_FORWARDED_FOR头,这是一个ip串,后端的真实服务器获取HTTP_X_FORWARDED_FOR头,截取字符串第一个不为unkown的IP作为用户真实IP地址, 例如:
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121(用户IP,CDN前端IP,CDN中转,公司NGINX代理)
getFor.php
<?php
$ip = getenv("HTTP_X_FORWARDED_FOR");
echo $ip;
?>
访问getFor.php结果如下:
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121
如果你是php程序员,你获取第一个不为unknow的ip地址,这边就是120.22.11.11.
安装nginx之时加上realip模块,我的参数如下:
./configure --prefix=/usr/local/nginx-1.4.1 --with-http_realip_module
真实服务器nginx配置
server {
listen 80;
server_name www.ttlsa.com;
access_log /data/logs/nginx/www.ttlsa.com.access.log main;
index index.php index.html index.html;
root /data/site/www.ttlsa.com;
location /
{
root /data/site/www.ttlsa.com;
}
location = /getRealip.php
{
set_real_ip_from 192.168.50.0/24;
set_real_ip_from 61.22.22.22;
set_real_ip_from 121.207.33.33;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
fastcgi_pass unix:/var/run/phpfpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
}
getRealip.php内容
<?php
$ip = $_SERVER['REMOTE_ADDR'];
echo $ip;
?>
访问www.ttlsa.com/getRealip.php,返回:
120.22.11.11
如果注释 real_ip_recursive on或者 real_ip_recursive off
访问www.ttlsa.com/getRealip.php,返回:
121.207.33.33
很不幸,获取到了中继的IP,real_ip_recursive的效果看明白了吧.
120.22.11.11,61.22.22.22,121.207.33.33,192.168.50.121
在real_ip_recursive on的情况下
61.22.22.22,121.207.33.33,192.168.50.121都出现在set_real_ip_from中,仅仅120.22.11.11没出现,那么他就被认为是用户的ip地址,并且赋值到remote_addr变量
在real_ip_recursive off或者不设置的情况下
192.168.50.121出现在set_real_ip_from中,排除掉,接下来的ip地址便认为是用户的ip地址
如果仅仅如下配置:
set_real_ip_from 192.168.50.0/24;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
访问结果如下:
121.207.33.33