1. 首页
  2. 技术知识

解决使用了nginx获取IP地址都是127.0.0.1 的问题

获取ip工具

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**

* IP地址

*

* @date 2022年3月6日 下午12:57:02

*/

@Slf4j

public class IPUtils {

    /**

     * 获取IP地址

     *

     * 使用Nginx等反向X软件, 则不能通过request.getRemoteAddr()获取IP地址

     * 如果使用了多级反向X的话,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);

        }

        //使用X,则获取第一个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

在X中加入如下配置proxy_set_header x-forwarded-for $remote_addr;

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地址问题内容请搜索共生网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持共生网络!

原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/106802.html

联系我们