Nginx 反为代理获取真实IP问题。Nginx 反朝代理获取真实IP问题。

一、前言

前文 Nginx
解决WebApi跨域二潮呼吁和Vue单页面问题
当中虽然缓解了跨域问题牵动的次不善呼吁,但为出了一个新的题目,就是设用取用户IP的当儿,获取的IP地址总是本机地址。

一、前言

前文 Nginx
解决WebApi跨域二不成呼吁和Vue单页面问题
当中虽然缓解了跨域问题带来的次差呼吁,但为闹了一个新的题目,就是要要取用户IP的时刻,获取的IP地址总是本机地址。

二、原因

由于Nginx反向代理后,在使用被落的IP且是倒为代理服务器的IP,取得的域名也是倒转往代理配置的Url的域名。

二、原因

由于Nginx反向代理后,在行使被获取的IP还是倒转为代理服务器的IP,取得的域名为是倒往代理配置的Url的域名。

老三、解决方案

釜底抽薪拖欠问题,需要以Nginx反向代理配置中上加有部署信息,目的将客户端的真IP和域名传递至应用程序中。同时,也要是修改得IP地址之章程。
然而要注意的凡,通过Nginx反向代理后,如果访问IP通过了几乎重叠代理,可能得到的IP地址是这种格式:clientIP,proxy1,proxy2
一经欲用IP地址插入到数据库的话,需要开防止流入。因此只要指向上述的IP地址的格式进行截取。

其三、解决方案

化解该问题,需要在Nginx反向代理配置中补充加有安排信息,目的将客户端的实事求是IP和域名传递到应用程序中。同时,也要改得IP地址的法。
而是急需留意的是,通过Nginx反向代理后,如果看IP通过了几乎层代理,可能取得的IP地址是这种格式:clientIP,proxy1,proxy2
若急需将IP地址插入到数据库的话,需要开防止流入。因此一旦针对性上述的IP地址之格式进行截取。

3.1 Nginx 配置如下

    server {
        listen       9461; # 监听端口号
        server_name  localhost 192.168.88.22; # 访问地址
        location / {
            root   项目路径; # 例如:E:/Publish/xxx/;
            index  index.html;

            # 此处用于处理 Vue、Angular、React 使用H5 的 History时 重写的问题
            if (!-e $request_filename) {
                rewrite ^(.*) /index.html last;
                break;
            }
        }

        # 代理服务端接口
        location /api {
            proxy_pass http://localhost:9460/api;# 代理接口地址
            # Host配置以及域名传递
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

3.1 Nginx 配置如下

    server {
        listen       9461; # 监听端口号
        server_name  localhost 192.168.88.22; # 访问地址
        location / {
            root   项目路径; # 例如:E:/Publish/xxx/;
            index  index.html;

            # 此处用于处理 Vue、Angular、React 使用H5 的 History时 重写的问题
            if (!-e $request_filename) {
                rewrite ^(.*) /index.html last;
                break;
            }
        }

        # 代理服务端接口
        location /api {
            proxy_pass http://localhost:9460/api;# 代理接口地址
            # Host配置以及域名传递
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

3.2 C#代码获取真实IP方法

#region Ip(客户端IP地址)

/// <summary>
/// 客户端IP地址
/// </summary>
public static string Ip
{
    get
    {
        var result = string.Empty;
        if (HttpContext.Current != null)
        {
            result = GetWebClientIp();
        }
        if (string.IsNullOrWhiteSpace(result))
        {
            result = GetLanIp();
        }
        return result;
    }
}

/// <summary>
/// 获取Web客户端的IP
/// </summary>
/// <returns></returns>
private static string GetWebClientIp()
{
    var ip = GetWebProxyRealIp() ?? GetWebRemoteIp();
    foreach (var hostAddress in Dns.GetHostAddresses(ip))
    {
        if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
        {
            return hostAddress.ToString();
        }
    }
    return string.Empty;
}

/// <summary>
/// 获取Web远程IP
/// </summary>
/// <returns></returns>
private static string GetWebRemoteIp()
{
    try
    {
        return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
               HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] ?? "";
    }
    catch (Exception e)
    {
        return string.Empty;
    }
}

/// <summary>
/// 获取Web代理真实IP
/// </summary>
/// <returns></returns>
private static string GetWebProxyRealIp()
{
    var request = HttpContext.Current.Request;
    string ip = request.Headers.Get("x-forwarded-for");

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.Headers.Get("Proxy-Client-IP");
    }

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.Headers.Get("WL-Proxy-Client-IP");
    }

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.UserHostAddress;
    }

    if (string.IsNullOrEmpty(ip))
    {
        return string.Empty;
    }
    // 可能存在如下格式:X-Forwarded-For: client, proxy1, proxy2
    if (ip.Contains(", "))
    {
        // 如果存在多个反向代理,获得的IP是一个用逗号分隔的IP集合,取第一个
        // X-Forwarded-For: client  第一个
        string[] ips = ip.Split(new string[1] {", "}, StringSplitOptions.RemoveEmptyEntries);
        var i = 0;
        for (i = 0; i < ips.Length; i++)
        {
            if (ips[i] != "")
            {
                // 判断是否为内网IP
                if (false == IsInnerIp(ips[i]))
                {
                    IPAddress realIp;
                    if (IPAddress.TryParse(ips[i], out realIp) && ips[i].Split('.').Length == 4)
                    {
                        //合法IP
                        return ips[i];
                    }

                    return "";
                }
            }
        }

        ip = ips[0];// 默认获取第一个IP地址
    }

    return ip;

}

/// <summary>
/// 判断IP地址是否为内网IP地址
/// </summary>
/// <param name="ip">IP地址</param>
/// <returns></returns>
private static bool IsInnerIp(string ip)
{
    bool isInnerIp = false;
    ulong ipNum = Ip2Ulong(ip);

    /**
     * 私有IP
     * A类:10.0.0.0-10.255.255.255
     * B类:172.16.0.0-172.31.255.255
     * C类:192.168.0.0-192.168.255.255
     * 当然,还有127这个网段是环回地址
     */

    ulong aBegin = Ip2Ulong("10.0.0.0");
    ulong aEnd = Ip2Ulong("10.255.255.255");
    ulong bBegin = Ip2Ulong("172.16.0.0");
    ulong bEnd = Ip2Ulong("10.31.255.255");
    ulong cBegin = Ip2Ulong("192.168.0.0");
    ulong cEnd = Ip2Ulong("192.168.255.255");

    isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) ||
                ip.Equals("127.0.0.1");
    return isInnerIp;
}

/// <summary>
/// 将IP地址转换为Long型数字
/// </summary>
/// <param name="ip">IP地址</param>
/// <returns></returns>
private static ulong Ip2Ulong(string ip)
{
    byte[] bytes = IPAddress.Parse(ip).GetAddressBytes();
    ulong ret = 0;
    foreach (var b in bytes)
    {
        ret <<= 8;
        ret |= b;
    }

    return ret;
}

/// <summary>
/// 判断用户IP地址转换为Long型后是否在内网IP地址所在范围
/// </summary>
/// <param name="userIp">用户IP</param>
/// <param name="begin">开始范围</param>
/// <param name="end">结束范围</param>
/// <returns></returns>
private static bool IsInner(ulong userIp, ulong begin, ulong end)
{
    return (userIp >= begin) && (userIp <= end);
}

/// <summary>
/// 获取局域网IP
/// </summary>
/// <returns></returns>
private static string GetLanIp()
{
    foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
        {
            return hostAddress.ToString();
        }
    }
    return string.Empty;
}
#endregion

3.2 C#代码获取真实IP方法

#region Ip(客户端IP地址)

/// <summary>
/// 客户端IP地址
/// </summary>
public static string Ip
{
    get
    {
        var result = string.Empty;
        if (HttpContext.Current != null)
        {
            result = GetWebClientIp();
        }
        if (string.IsNullOrWhiteSpace(result))
        {
            result = GetLanIp();
        }
        return result;
    }
}

/// <summary>
/// 获取Web客户端的IP
/// </summary>
/// <returns></returns>
private static string GetWebClientIp()
{
    var ip = GetWebProxyRealIp() ?? GetWebRemoteIp();
    foreach (var hostAddress in Dns.GetHostAddresses(ip))
    {
        if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
        {
            return hostAddress.ToString();
        }
    }
    return string.Empty;
}

/// <summary>
/// 获取Web远程IP
/// </summary>
/// <returns></returns>
private static string GetWebRemoteIp()
{
    try
    {
        return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
               HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] ?? "";
    }
    catch (Exception e)
    {
        return string.Empty;
    }
}

/// <summary>
/// 获取Web代理真实IP
/// </summary>
/// <returns></returns>
private static string GetWebProxyRealIp()
{
    var request = HttpContext.Current.Request;
    string ip = request.Headers.Get("x-forwarded-for");

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.Headers.Get("Proxy-Client-IP");
    }

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.Headers.Get("WL-Proxy-Client-IP");
    }

    if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
    {
        ip = request.UserHostAddress;
    }

    if (string.IsNullOrEmpty(ip))
    {
        return string.Empty;
    }
    // 可能存在如下格式:X-Forwarded-For: client, proxy1, proxy2
    if (ip.Contains(", "))
    {
        // 如果存在多个反向代理,获得的IP是一个用逗号分隔的IP集合,取第一个
        // X-Forwarded-For: client  第一个
        string[] ips = ip.Split(new string[1] {", "}, StringSplitOptions.RemoveEmptyEntries);
        var i = 0;
        for (i = 0; i < ips.Length; i++)
        {
            if (ips[i] != "")
            {
                // 判断是否为内网IP
                if (false == IsInnerIp(ips[i]))
                {
                    IPAddress realIp;
                    if (IPAddress.TryParse(ips[i], out realIp) && ips[i].Split('.').Length == 4)
                    {
                        //合法IP
                        return ips[i];
                    }

                    return "";
                }
            }
        }

        ip = ips[0];// 默认获取第一个IP地址
    }

    return ip;

}

/// <summary>
/// 判断IP地址是否为内网IP地址
/// </summary>
/// <param name="ip">IP地址</param>
/// <returns></returns>
private static bool IsInnerIp(string ip)
{
    bool isInnerIp = false;
    ulong ipNum = Ip2Ulong(ip);

    /**
     * 私有IP
     * A类:10.0.0.0-10.255.255.255
     * B类:172.16.0.0-172.31.255.255
     * C类:192.168.0.0-192.168.255.255
     * 当然,还有127这个网段是环回地址
     */

    ulong aBegin = Ip2Ulong("10.0.0.0");
    ulong aEnd = Ip2Ulong("10.255.255.255");
    ulong bBegin = Ip2Ulong("172.16.0.0");
    ulong bEnd = Ip2Ulong("10.31.255.255");
    ulong cBegin = Ip2Ulong("192.168.0.0");
    ulong cEnd = Ip2Ulong("192.168.255.255");

    isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) ||
                ip.Equals("127.0.0.1");
    return isInnerIp;
}

/// <summary>
/// 将IP地址转换为Long型数字
/// </summary>
/// <param name="ip">IP地址</param>
/// <returns></returns>
private static ulong Ip2Ulong(string ip)
{
    byte[] bytes = IPAddress.Parse(ip).GetAddressBytes();
    ulong ret = 0;
    foreach (var b in bytes)
    {
        ret <<= 8;
        ret |= b;
    }

    return ret;
}

/// <summary>
/// 判断用户IP地址转换为Long型后是否在内网IP地址所在范围
/// </summary>
/// <param name="userIp">用户IP</param>
/// <param name="begin">开始范围</param>
/// <param name="end">结束范围</param>
/// <returns></returns>
private static bool IsInner(ulong userIp, ulong begin, ulong end)
{
    return (userIp >= begin) && (userIp <= end);
}

/// <summary>
/// 获取局域网IP
/// </summary>
/// <returns></returns>
private static string GetLanIp()
{
    foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
        {
            return hostAddress.ToString();
        }
    }
    return string.Empty;
}
#endregion

相关文章

admin

网站地图xml地图