nginx代理后java获取真实ip解决办法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gdutsmkf/article/details/48651857

nginx代理的时候,tomcat获取的客户端不是客户端传过来的ip,出现这种情况的原因很明显,

nginx作为代理服务器先拦截客户端发来的请求,

它再以localhost的身份转发给tomcat去处理。

解决办法在nginx配置中的location节点中加入以下: 

        proxy_set_header Host $host; 

        proxy_set_header X-Real-IP $remote_addr; 

        proxy_set_header REMOTE-HOST $remote_addr; 

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

修改位置截图

JAVA端可用以下方法获取用户真实IP

public String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		log.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip="
				+ ip);
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
				log.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip="
						+ ip);
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
				log.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip="
						+ ip);
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
				log.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip="
						+ ip);
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
				log.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip="
						+ ip);
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
				log.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip="
						+ ip);
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}


阅读更多
换一批

没有更多推荐了,返回首页