nginx如何获取真实的ip

我这里使用是springboot项目,使用nginx做代理,但header里面的参数没有将ip带过来,所有需要配置nginx将ip带过来。

nginx.conf文件


server {
    listen       80;
    listen       443 ssl;
    server_name  xxx.xxx.com;
    ssl_certificate  /web/project/ai-master/ssl/xxx.xxx.com_bundle.pem;
    ssl_certificate_key  /web/project/ai-master/ssl/xxx.xxx.com.top.key;

    #接口
    location /api {

        #保留代理之前的host 包含客户端真实的域名和端口号
        proxy_set_header    Host  $host;
        #保留代理之前的真实客户端ip
        proxy_set_header    X-Real-IP  $remote_addr;
        #这个Header和X-Real-IP类似,但它在多级代理时会包含真实客户端及中间每个代理服务器的IP
        proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
        #表示客户端真实的协议(http还是https)
        proxy_set_header X-Forwarded-Proto $scheme;
        
        proxy_pass http://aiMasterServer/api;
    }

}

RequestUtil.java文件


/**
 * @Description:请求处理类
 * @author: Adobe Chow
 * @date: 2019/4/25 10:42
 * @Copyright: www.winshang.com Inc. All rights reserved.
 */
public class RequestUtil {

    public static HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static HttpServletResponse getResponse(){
        HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /***
     * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP,
     * @return
     */
    public static String getClientIP() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

你可能感兴趣的:(nginx,tcp/ip,运维)