Apache做后端如何获取前端传来的真实IP信息

发布于 2014-03-17  94 次阅读


首先Nginx里面需要配置一下

proxy_pass http://IP:端口;
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是你的Nginx反带后端的地址,根据自己的需要填写IP和端口吧!
下面就是把真实的IP地址封装到请求头里面带过去,然后Apache这家伙居然傻不拉几的自己不会辨别-。-
这就需要安装一个模块”rpaf”
rpaf的最新版本在这http://www.stderr.net/apache/rpaf/(注:此链接已失效,可以通过此链接下载然后scp上去http://ishare.iask.sina.com.cn/f/34347504.html)大家可以自己去下载!

wget http://www.stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz
tar zxf mod_rpaf-0.6.tar.gz
cd mod_rpaf-0.6
apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c

注意里面的路径,千万不要弄错了!这个路径在执行完上面的命令之后会在回显的末尾给出,注意观察。

然后就在你的apache 里面配置一下即可

LoadModule rpaf_module /usr/local/apache/modules/mod_rpaf-2.0.so
RPAFenable On
RPAFsethostname On
RPAFproxy_ips IP地址 (nginx前端地址)
RPAFheader X-Forwarded-For
路径不要错啦,还有就是ip要和nginx的ip填写的一样,就是和proxy_pass http://IP:端口;这里的IP要一样。

剩下的就是重启一下服务了。搞定!

以上参考自:http://blog.sina.com.cn/s/blog_4560b80b0100m79m.html
==============================================================
本来按照这个说明能完成的,但我的后端是apache2.4的,所以遇到了错误:
apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c
/var/www/build/libtool --silent --mode=compile gcc -std=gnu99 -prefer-pic -DLINUX -D_REENTRANT -D_GNU_SOURCE -g -O2 -pthread -I/usr/include/apache -I/usr/include/apache -I/usr/include/apache -c -o mod_rpaf-2.0.lo mod_rpaf-2.0.c && touch mod_rpaf-2.0.slo
mod_rpaf-2.0.c: In function 'rpaf_cleanup':
mod_rpaf-2.0.c:150: error: 'conn_rec' has no member named 'remote_ip'
mod_rpaf-2.0.c:151: error: 'conn_rec' has no member named 'remote_addr'
mod_rpaf-2.0.c:151: warning: implicit declaration of function 'inet_addr'
mod_rpaf-2.0.c:151: error: 'conn_rec' has no member named 'remote_ip'
mod_rpaf-2.0.c: In function 'change_remote_ip':
mod_rpaf-2.0.c:164: error: 'conn_rec' has no member named 'remote_ip'
mod_rpaf-2.0.c:183: error: 'conn_rec' has no member named 'remote_ip'
mod_rpaf-2.0.c:186: error: 'conn_rec' has no member named 'remote_ip'
mod_rpaf-2.0.c:187: error: 'conn_rec' has no member named 'remote_addr'
mod_rpaf-2.0.c:187: error: 'conn_rec' has no member named 'remote_ip'
apxs:Error: Command failed with rc=65536
.

在一个博客里(http://blog.77jp.net/mod_rpaf-install-apache-2-4)找到了解决方法:
如果是apache2.4请执行这个:

git clone git://gist.github.com/2716030.git

如果没找到git就yum install git-core 或者 apt-get install git-core

然后运行这个
patch < 2716030/mod_rpaf-2.0.c.patch

command not found: patch

如果出现上面的提示就运行这个

yum install patch 或 apt-get install patch

最后执行

/usr/local/apache2/bin/apxs -i -c mod_rpaf-2.0.so mod_rpaf-2.0.c

apxs -i -c mod_rpaf-2.0.so mod_rpaf-2.0.c