Nginx配置方案
1. 确认已安装http_realip_module模块
为实现负载均衡,Nginx使用http_realip_module模块来获取真实IP。
您可以通过执行# nginx -V | grep http_realip_module命令查看是否已安装该模块。如未安装,则需要重新编译Nginx服务并加装该模块。
说明 一般情况下,如果通过一键安装包安装Nginx服务器,默认不安装该模块。
参考以下方法,安装 http_realip_module模块:
wget http://nginx.org/download/nginx-1.12.2.tar.gztar zxvf nginx-1.12.2.tar.gzcd nginx-1.12.2./configure --user=www --group=www --prefix=/alidata/server/nginx --with-http_stub_status_module --without-http-cache --with-http_ssl_module --with-http_realip_modulemake
make install
kill -USR2 `cat /alidata/server/nginx/logs/nginx.pid`
kill -QUIT `cat /alidata/server/nginx/logs/ nginx.pid.oldbin`
2. 修改Nginx对应server的配置
打开default.conf配置文件,在location / {}中添加以下内容:
说明
其中,ip_range1,2,...,x指WAF的回源IP地址,需要分多条分别添加。
set_real_ip_from ip_range1;set_real_ip_from ip_range2;...
set_real_ip_from ip_rangex;real_ip_header X-Forwarded-For;
3. 修改日志记录格式 log_format
log_format一般在nginx.conf配置文件中的http配置部分。在 log_format中,添加 x-forwarded-for字段,替换原来remote-address字段,即将 log_format修改为以下内容:
log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" ';
完成以上操作后,执行nginx -s reload命令重启Nginx服务。配置生效后,Nignx服务器即可通过X-Forwarded-For的方式记录访问者真实IP。