http { 放到http下
# for pre-open closed test
map $http_x_forwarded_for $allowed {
default deny;
~\s*111.222.333.444$ allow;
~\s*123.456.789.*$ allow;
}
}
location / {
if ($allowed = "deny") { return 403; }
alias /path/to/document_root
}
===========================================
nginx http_realip_module模块
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;
}
set_real_ip_from:真实服务器上一级代理的IP地址或者IP段,可以写多行
real_ip_header:从哪个header头检索出要的IP地址
real_ip_recursive:递归排除IP地址,ip串从右到左开始排除set_real_ip_from里面出现的IP,如果出现了未出现这些ip段的IP,
那么这个IP将被认为是用户的IP。例如我这边的例子,真实服务器获取到的IP地址串如下:
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
使用realip获取
优点:程序不需要改动,直接使用remote_addr即可获取IP地址
缺点:ip地址有可能被伪装,而且需要知道所有CDN节点的ip地址或者ip段
或者 set_real_ip_from 0.0.0.0/0; 待验证