Apache通过mod_remoteip模块获取客户端IP地址

前端采用nginx,后端采用apache处理php动态请求,这时候遇到一个问题就是后端apache获取真实用户ip的问题,默认不做配置获取到的是前端nginx的ip地址,解决办法是通过mod_remoteip模块获取真实ip。

apache 2.4自带mod_remoteip模块不需要安装,添加如下文件配置

# vim /usr/local/apache/conf/httpd.conf

启用模块

Include conf/extra/httpd-remoteip.conf

# vim /usr/local/apache/conf/extra/httpd-remoteip.conf

添加如下内容

LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1

修改日志格式,在日志格式中加上%a

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" combined

然后重启apache即可

apache 2.2 需要安装,安装方法如下:

# 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
# vim /usr/local/apache/conf/httpd.conf

启用模块

Include conf/extra/httpd-remoteip.conf

# vim /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即可