ytfcz

当用户 与 tomcat之间 用 nginx做跳转时,

HttpServletRequest 中的 getRemoteHost()方法获取到的只是nginx的地址,而不能拿到用户真正的请求地址

 

解决方式 :

第一步 ,nginx 的 nginx.conf配置文件中:

location ~ ^/site {

  proxy_pass http://localhost:8088;

  proxy_set_header  X-Real-IP  $remote_addr;   // 主要添加这一句代码

}

第二步 ,服务端添加一个过滤器,主要方法如下:

public void setRemoteAddrIp(HttpServletRequest request) {

        String ipFromNginx = getHeader(request, "X-Real-IP");

        System.out.println("ipFromNginx:" + ipFromNginx);

        System.out.println("getRemoteAddr:" + request.getRemoteAddr());

        request.setAttribute("remoteIP" , StringUtils.isBlank(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx);

}

private String getHeader(HttpServletRequest request, String headName) {

        String value = request.getHeader(headName);

        return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";

}

 

如果tomcat日志中也需要存储远程地址,在tomcat的配置文件中配置以下内容:

<Valve className="org.apache.catalina.valves.AccessLogValve"
                 directory="logs"  prefix="tomcat_access_log." suffix=".txt"
                 pattern="%a %r %t %{X-Real_IP}i" resolveHosts="false"/>

分类:

技术点:

相关文章:

  • 2021-10-07
  • 2021-12-10
  • 2019-11-22
  • 2021-08-05
  • 2021-09-15
  • 2021-09-27
  • 2021-11-08
猜你喜欢
  • 2021-09-10
  • 2021-11-07
  • 2021-08-03
  • 2021-09-27
  • 2021-09-27
  • 2021-09-10
  • 2019-03-28
相关资源
相似解决方案