前端Nginx,后端Apache获取用户真实IP地址

nginx作为前端,Apache作为后端的情况下,Apache只能获取到Nginx前端的ip地址(127.0.0.1),而无法获取到用户的真实ip地址,在这种情况下,后端是Apache如何获取用户真实IP地址?

前端nginx加了如下配置后

proxy_pass https://10.10.30.237:443;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

你会发现后端也获取不到真实的IP,只会获得前端的IP

获取真实IP地址有Apache有2个模块:
mod_rpaf:Apache-2.2支持;Apache-2.4不支持。网上教程很多
mod_remoteip:Apache-2.4自带模块;Apache-2.2支持;推荐

Apache-2.2下配置mod_remoteip如下:
安装

wget https://github.com/ttkzw/mod_remoteip-httpd22/raw/master/mod_remoteip.c
/usr/local/apache/bin/apxs -i -c -n mod_remoteip.so mod_remoteip.c

修改配置文件:

vi /usr/local/apache/conf/httpd.conf
Include conf/extra/httpd-remoteip.conf
vi /usr/local/apache/conf/extra/httpd-remoteip.conf
LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1

Apache-2.4配置mod_remoteip除了上面(自带mod_remoteip模块不需要安装),还需要修改日志格式(折腾很久)

LogFormat "%h %a %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
LogFormat "%h %a %l %u %t "%r" %>s %b" common
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %I %O" combinedi

在日志格式中加上%a

木易的技术记录 » 前端Nginx,后端Apache获取用户真实IP地址

顶 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

置顶文章