nginx无法获取真实ip的问题

来源:互联网 发布:假病例制作软件 编辑:程序博客网 时间:2024/05/29 07:44

使用“Web应用防火墙”后获取访问者真实IP配置指南

很多时候,网站并不是简单的从用户的浏览器直达服务器, 中间可能会加入CDN、WAF、高防。

从而,变成如下的架构:

用户 —–> CDN/WAF/高防 ——> 源站服务器

那么,经过这么多层加速,服务器如何才能得到发起请求的真实客户端IP呢?

当一个透明代理服务器把用户的请求转到后面服务器的时候,会在HTTP的头中加入一个记录:

X-Forwarded-For:用户真实IP

如果中间经历了不止一个代理服务器,那么X-Forwarded-For可能会为以下的形式:

X-Forwarded-For:用户IP, 代理服务器1-IP, 代理服务器2-IP, 代理服务器3-IP, ……

获取来访真实IP方法

因此,常见应用服务器获取来访者真实IP可通过如下方法实现。

  • 使用X-Forwarded-For的方式获取访问者真实IP

以下针对常见的应用服务器配置方案进行介绍:


Nginx配置方案

1. 确认http_realip_module模块已安装

Nginx作为负载均衡获取真实IP是使用http_realip_module,通过默认一键安装包安装的Nginx是没有安装这个模块的。您可以执行# nginx -V | grep http_realip_module 命令查看该模块是否已安装。

如没有安装,则需要重新重新编译Nginx并加装,您可参考以下方法进行安装:

  1. wget http://nginx.org/download/nginx-1.12.2.tar.gz
  2. tar zxvf nginx-1.12.2.tar.gz
  3. cd nginx-1.12.2
  4. ./configure --user=www --group=www --prefix=/alidata/server/nginx --with-http_stub_status_module --without-http-cache --with-http_ssl_module --with-http_realip_module
  5. make
  6. make install
  7. kill -USR2 `cat /alidata/server/nginx/logs/nginx.pid`
  8. kill -QUIT `cat /alidata/server/nginx/logs/ nginx.pid.oldbin`

2. 修改Nginx对应server的配置(如默认的是default.conf)

location / {}中添加:

  1. set_real_ip_from ip_range1;
  2. set_real_ip_from ip_range2;
  3. ...
  4. set_real_ip_from ip_rangex;
  5. real_ip_header X-Forwarded-For;

这里的ip_range1,2,…指的是WAF的回源IP地址,需要添加多条。

3. 修改日志记录格式 log_format

log_format一般在nginx.conf中的http配置中:

  1. log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" ';

即将x-forwarded-for字段加进去,替换掉原来的remote-address,添加后效果如下图:

log_format

最后重启Nginx使配置生效:nginx -s reload


nginx识别cdn和云盾的真实ip靠的是http_realip_module

其实只要在编译nginx的参数后面加上 –with-http_realip_module,nginx就具备识别cdn和云盾真实ip的能力啦。当然,你还要在nginx.conf里添加必要的配置代码哦:

我使用的是阿里云云盾,下面是我的代码:

http{

set_real_ip_from 42.121.43.0/24;
set_real_ip_from 127.0.0.1;
set_real_ip_from 10.242.174.13;
real_ip_header X-Forwarded-For;

}

如果你使用的是诸如百度云加速之类的cdn,就把42.121.43.0/24的ip段及ip地址,更换为百度云加速的ip。关于wdcp下nginx升级到任意版本以及编译http_realip_module的脚本。


原创粉丝点击