Nginx反向代理下的IP获取异常与解决方案
IP地址获取工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* IP地址
*
* @date 2026年3月6日 下午12:57:02
*/
@Slf4j
public class IPUtils {
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("IPUtils ERROR ", e);
}
//使用代理,则获取第一个IP地址
if(StringUtils.isEmpty(ip) && ip.length() > 15) {
if(ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
}
当项目部署在Nginx等反向代理之后,直接调用标准方法获取的IP地址通常会错误地显示为127.0.0.1,即本地回环地址。
为解决这一问题,需要在Nginx的配置文件中的location块内添加特定指令:proxy_set_header x-forwarded-for $remote_addr;,以便将客户端真实IP传递给后端服务。
server {
listen 80;
server_name api.qimen.pro;
# 服务器文件上传大小限制
client_max_body_size 10M;
location / {
proxy_pass http://gymserver;
proxy_set_header x-forwarded-for $remote_addr;
}
}
到此这篇关于解决使用了nginx获取IP地址都是127.0.0.1 的问题的文章就介绍到这了,更多相关nginx获取IP地址问题内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!