应用程序部署上线,一般都会用nginx之类的来进行反向代理,而不是直接访问tomcat之类的容器.
这时候如果用平时的获取ip的代码,就只会获取到nginx所在服务器的ip, 就失去了本身的意义.
今天就来配置下 nginx+tomcat 后, 程序获取ip和 tomcat的访问日志localhost_access_log 获取ip.
1.首先要在nginx中加个配置,即把用户ip保存下来
在nginx的配置文件中增加
1
| proxy_set_header X-real-ip $remote_addr;
|
各位置要注意, 可以放在 location / 中, 如果你配置了.do, .action的转发, 那就要放在 .do,.action的配置中
2.修改程序中获取ip的方法,先取 X-real-ip的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-real-ip"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("x-forwarded-for"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
|
3.修改tomcat的日志配置,记录访问的来源ip
在server.xml中,修改AccessLogValve的配置如下
1 2 3
| <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%{yyyy-MM-dd HH:mm:ss}t %{X-real-ip}i "%r" %s %b %{User-Agent}i" />
|