• nginx ngx_http_realip 的功能以及使用


    网上关于ngx_http_realip 使用介绍的基本都是一个老生长谈的问题了,对于多级代理配置的这个就是一个常用的解决用户真实ip的方法,以下是使用
    的一个简单说明

    ngx_http_realip 简单说明

    ngx_http_realip 是一个获取用户请求真实ip 的一个模块,可以在多代理链路场景下解决我们获取真实ip 的问题

    参考使用

    • 指令配置
     
    set_real_ip_from  192.168.1.0/24;
    set_real_ip_from  192.168.2.1;
    set_real_ip_from  2001:0db8::/32;
    real_ip_header    X-Forwarded-For;
    real_ip_recursive on;
    • 简单说明

    set_real_ip_from 定义可信ip,实际上就是会自动从请求头中去掉的,可以配置多个,同时可以支持ipv4,ipv6以及cidr 格式的
    real_ip_header 制定我们获取真实ip 的的请求方式,包含了标准玩法的 X-Forwarded-For,X-Real-IP,proxy_protocol,当然也是可以自定义,此参数需要我们也
    上级代理进行协商
    请求header的,比如适合有特定需求的(cdn 比较多)
    real_ip_recursive off 会将请求头的中最后一个ip 作为真实ip

    处理的阶段

    • 参考源码处理

    从上边可以看出来,是在post_read 阶段的,同时也在在pre_access阶段,所以如果我们使用了是access 处理的服务的(包含openresty),而且存在多级代理
    配置此模块就比较重要了,而且ngx_http_realip 是优先与access的,所以我们就能处理真确的ip,保证我们基于access 阶段处理的基于ip 的防护策略是可以正常工作的

     
    static ngx_int_t
    ngx_http_realip_init(ngx_conf_t *cf)
    {
        ngx_http_handler_pt        *h;
        ngx_http_core_main_conf_t  *cmcf;
     
        cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
       // post_read 阶段
        h = ngx_array_push(&cmcf->phases[NGX_HTTP_POST_READ_PHASE].handlers);
        if (h == NULL) {
            return NGX_ERROR;
        }
     
        *h = ngx_http_realip_handler;
      // pre_access 阶段
        h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
        if (h == NULL) {
            return NGX_ERROR;
        }
     
        *h = ngx_http_realip_handler;
     
        return NGX_OK;
    }

    说明

    学习东西结合源码,了解内部工作机制会比较重要,对于我们排错以及工作使用会有很大的帮助

    参考资料

    https://nginx.org/en/docs/http/ngx_http_realip_module.html
    https://nginx.org/en/docs/http/ngx_http_access_module.html

  • 相关阅读:
    Mockito一个方法的实例
    LIst与ArrayList区别
    mockito入门学习
    eclipse中调整字体大小和改变背景颜色
    常用sql语句
    eclipse导入代码和重新编译
    windows下登录linux的常用工具SecureCRT和常用命令
    junit4
    接口测试
    java环境
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/16280390.html
Copyright © 2020-2023  润新知