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

posted on   荣锋亮  阅读(400)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-05-17 promcat.io 由sysdig 托管的企业级prometheus监控网站
2020-05-17 c 语言使用lttng
2020-05-17 lttng简单试用
2020-05-17 dotnetcore 性能分析一些文章
2019-05-17 edgedb-js 来自官方的js 驱动
2019-05-17 edgedb 开发环境运行

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示