官方說明:html
例子:java
虛擬機ip:192.168.85.3,物理機VMware Network Adapter VMnet8 ip:192.168.85.1nginx
1,準備tomcat瀏覽器
準備一tomcat,端口,8080
tomcat
準備一Jsp,用於獲取客戶端真實IP和nginx IP ,test.jsp:服務器
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test Page</title> </head> <body> Test1 Page!!!<br/> remote ip : <%-- <%=request.getHeader("X-real-ip") %> --%> <br/> nginx server ip : <%=request.getRemoteAddr()%> </body> </html>
將test.jsp 上傳到 tomcat的/ROOT目錄下。jsp
2,配置nginx工具
注意,反向代理以後獲取到客戶端IP地址爲nginx服務器地址,這裏須要nginx進行forward,設置真實的ip地址。往請求頭set一變量 X-real-ip ,值取客戶端ip,這樣就能夠在jsp中獲取該變量:測試
proxy_set_header X-real-ip $remote_addr; ui
匹配.jsp結尾的請求:
location ~ \.jsp$
3,測試
啓動tomcat,啓動nginx,瀏覽器訪問:http://192.168.85.3:70/test.jsp
在Java裏面通常有一個工具類來獲取 IP:
public class IpUtils { private IpUtils() { } public static String getIpAddr(HttpServletRequest request) { if (request == null) { return "unknown"; } String 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("X-Forwarded-For"); } 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.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }