经过NGINX反向代理,后端服务器获取不了真实IP

原因:通过了Apache,Squid,nginx等反向代理软件就不能获取到客户端的真实IP地址了。经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP(拿到的是中间层的ip),服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了x-forwarded-for信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。

解决:在NGINX反向代理服务器上进行修改

在nginx配置文件中

每一个location上加上以下

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

重启nginx即可

springboot获取ip

/**
* 获取登录用户的IP地址
*
* @param request
* @return
*/

public static String getIp(HttpServletRequest request) {
if (request == null)
return "";
String ip = request.getHeader("X-Requested-For");
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (Strings.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}

if("0:0:0:0:0:0:0:1".equals(ip)){
return "127.0.0.1";
}
return ip;
}

public static boolean isLocalHost(String ip){
return "127.0.0.1".equals(ip) || "localhost".equals(ip);
}
/**
* 解析ip地址
*
* @param ipAddress
* @return
*/
public static String getIpSource(String ipAddress) {
try {
URL url = new URL("http://opendata.baidu.com/api.php?query=" + ipAddress + "&co=&resource_id=6006&oe=utf8");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "utf-8"));
String line = null;
StringBuffer result = new StringBuffer();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
Map map = JSON.parseObject(result.toString(), Map.class);
List<Map<String, String>> data = (List) map.get("data");
return data.get(0).get("location");
} catch (Exception e) {
return "";
}
}