用nginx代理的配置

添加配置
image.png

  1. proxy_set_header Host $host$server_port;
  2. proxy_set_header X-Real-IP $remote_addr;
  3. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  4. proxy_set_header X-Forwarded-Proto $scheme;

代码

  1. public static String getClientIpAddress(HttpServletRequest request) {
  2. // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
  3. String headerName = "x-forwarded-for";
  4. String ip = request.getHeader(headerName);
  5. if (null != ip && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
  6. // 多次反向代理后会有多个IP值,第一个IP才是真实IP,它们按照英文逗号','分割
  7. if (ip.indexOf(",") != -1) {
  8. ip = ip.split(",")[0];
  9. }
  10. }
  11. if (checkIp(ip)) {
  12. headerName = "Proxy-Client-IP";
  13. ip = request.getHeader(headerName);
  14. }
  15. if (checkIp(ip)) {
  16. headerName = "WL-Proxy-Client-IP";
  17. ip = request.getHeader(headerName);
  18. }
  19. if (checkIp(ip)) {
  20. headerName = "HTTP_CLIENT_IP";
  21. ip = request.getHeader(headerName);
  22. }
  23. if (checkIp(ip)) {
  24. headerName = "HTTP_X_FORWARDED_FOR";
  25. ip = request.getHeader(headerName);
  26. }
  27. if (checkIp(ip)) {
  28. headerName = "X-Real-IP";
  29. ip = request.getHeader(headerName);
  30. }
  31. if (checkIp(ip)) {
  32. headerName = "remote addr";
  33. ip = request.getRemoteAddr();
  34. // 127.0.0.1 ipv4, 0:0:0:0:0:0:0:1 ipv6
  35. if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
  36. //根据网卡取本机配置的IP
  37. InetAddress inet = null;
  38. try {
  39. inet = InetAddress.getLocalHost();
  40. } catch (UnknownHostException e) {
  41. LOGGER.error("getClientIp getLocalHost error " + e);
  42. e.printStackTrace();
  43. }
  44. ip = inet.getHostAddress();
  45. }
  46. }
  47. LOGGER.info("getClientIp IP is " + ip + ", headerName = " + headerName);
  48. return ip;
  49. }
  50. private static boolean checkIp(String ip) {
  51. if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  52. return true;
  53. }
  54. return false;
  55. }