nginx 在多层代理下获取客户端IP

nginx在有多层代理中,X-Forwarded-For头部会包含多个IP,比如这种:

120.22.11.11,  61.22.22.22,  121.207.33.33,192.  168.50.121(用户IP,CDN前端IP,CDN中转,公司NGINX代理)

在这种情况下,日志无法上报到ELK系统。
本文介绍如何利用nginx lua模块,获取用户的真实Ip。

  • lua代码
local ip_str = ngx.var.http_x_forwarded_for

if ip_str then
    local regex = [[\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}]]
     -- 参数 "j" 启用 JIT 编译,参数 "o" 是开启缓存必须的
    local m = ngx.re.match(ip_str, regex, "jo")
    return m[0]
else
    return ngx.var.remote_addr 
end
  • NGINX配置
set_by_lua_file $my_remote_ip /usr/local/openresty/nginx/parse_ip.lua;

  • 日志中使用这个变量
   log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $upstream_response_time $request_time $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$my_remote_ip" $traceid';

参考文档:
https://moonbingbing.gitbooks.io/openresty-best-practices/content/lua/re.html
https://blog.51cto.com/wenzengliu/1642371

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容