nginx设置
location / {
root html;
index index.html index.htm;
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
Java获取被nginx反向代理后客户端的真实IP
package com.songlong.love.utils; import javax.servlet.http.HttpServletRequest; public class IpUtil { //获取客户端真实IP地址 public static String getRemoteAddress(HttpServletRequest request) { String unknown = "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("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } 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(); } //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ip != null && ip.length() > 0) { String[] ips = ip.split(","); if (ips.length > 0) { ip = ips[0]; } } return ip; } }
spring boot获取当前请求的请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
版权声明:本文为qq_42838143原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。