https://www.cnblogs.com/powerwu/articles/12978664.html

配置 Nginx

如果你的 Java 项目使用了 Nginx 代理,那么还需要进行以下配置,才能顺利获取到真实的 IP,否则只能获取到 127.0.0.1
在 Nginx 的配置文件里,找到你 Java 项目的配置,在 location 里添加以下代码:

  1. proxy_set_header X-Real-IP $remote_addr;
  2. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

注意:修改 Nginx 配置文件后,需要重新加载配置文件(nginx -s reload)。

$remote_addr :与$http_x_forwarded_for用以记录客户端的ip地址;
$remote_user :记录客户端用户的名称;
$time_local :访问时间及时区;
$request :请求的URL与HTTP协议;
$status :记录请求状态
$body_bytes_sent:记录发送给客户端文件主体内容大小;
$http_referer:用来记录从那个页面链接访问过来的;
$http_user_agent:记录客户端浏览器的相关信息
access_log /usr/local/nginx/var/log/access.log main ; 这句话是日志文件存放的位置

java代码

  1. public class IpUtil {
  2. public static String getIpAddr(HttpServletRequest request) {
  3. String ipAddress = null;
  4. try {
  5. ipAddress = request.getHeader("x-forwarded-for");
  6. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  7. ipAddress = request.getHeader("Proxy-Client-IP");
  8. }
  9. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  10. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  11. }
  12. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  13. ipAddress = request.getRemoteAddr();
  14. if (ipAddress.equals("127.0.0.1")) {
  15. // 根据网卡取本机配置的IP
  16. InetAddress inet = null;
  17. try {
  18. inet = InetAddress.getLocalHost();
  19. } catch (UnknownHostException e) {
  20. e.printStackTrace();
  21. }
  22. ipAddress = inet.getHostAddress();
  23. }
  24. }
  25. // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  26. if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
  27. // = 15
  28. if (ipAddress.indexOf(",") > 0) {
  29. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  30. }
  31. }
  32. } catch (Exception e) {
  33. ipAddress="";
  34. }
  35. // ipAddress = this.getRequest().getRemoteAddr();
  36. return ipAddress;
  37. }
  38. }
  1. public String getIpAddress(HttpServletRequest request) {
  2. String ip = request.getHeader("x-forwarded-for");
  3. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  4. ip = request.getHeader("Proxy-Client-IP");
  5. }
  6. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  7. ip = request.getHeader("WL-Proxy-Client-IP");
  8. }
  9. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  10. ip = request.getHeader("HTTP_CLIENT_IP");
  11. }
  12. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  13. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  14. }
  15. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  16. ip = request.getRemoteAddr();
  17. }
  18. return ip;
  19. }