Jusene's Blog

多层代理透传真实ip

字数统计: 440阅读时长: 2 min
2017/06/19 Share

今天面对一个难题,如何在阿里的负载均衡经由nginx再做层代理,如何让tomcat获取到真正的客户端ip,如果只是一层代理这个实现起来会很容易,但是经过多层代理,按照普通的办法我们拿到ip会是第一层代理的ip,经过一番摸索,我找到了nginx的http_realip_module的模块可以完成这个功能。

nginx官网文档对http_realip_module的解释是:
“It is useful if nginx works behind some proxy of L7 load balanver, and request come from local IP, but proxy add request header with client’s IP.This module isn’t built by default, enable it with the configure option ”

编译模块

nginx采用模块化设计,但是不支持动态装载模块,所以我们还是需要编译下nginx的源码包:

1
~]# cd nginx-1.9.12
2
~}# ./configure --prefix=/data/nginx --with-http_stub_status_module --with-http_ssl_module --user=www --group=www --with-http_realip_module
3
~]# make
4
~]# cp -f ./objs/nginx /data/nginx/sbin/
5
~]# cd /data/nginx/sbin/
6
~]# ./nginx -t
7
~]# ./nginx -s reload
8
~]# ./nginx -V
9
nginx version: nginx/1.9.12
10
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC) 
11
built with OpenSSL 1.0.1e-fips 11 Feb 2013
12
TLS SNI support enabled
13
configure arguments: --prefix=/data/nginx --with-http_stub_status_module --with-http_ssl_module --user=www --group=www --with-http_realip_module

代理配置

1
~]# vim proxy.conf
2
server {
3
	listen 80;
4
	server_name api.jusene.me;
5
	location / {
6
		proxy_pass http://127.0.0.1:8080;
7
		proxy_set_header Host $host;
8
		proxy_set_header X-Forwarded-For $remote_addr;
9
		set_real_ip_from 101.37.106.55;   #ip为阿里负载均衡器的ip
10
		real_ip_header X-Forwarded-For;   #从阿里负载均衡器的X-Forwarded-For获取真正的ip
11
	}
12
}

tomcat

1
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
2
               prefix="localhost_access_log." suffix=".txt"
3
               pattern="%{X-Forwarded-For}i %l %u %t "%r" %s %b" />
CATALOG
  1. 1. 编译模块
  2. 2. 代理配置
  3. 3. tomcat