limit_local_access.lua 911 Bytes
-- author: chunhua.zhang
-- only allow request from local ip 
-- depends on param: [ngx.var.real_ip], which should be setted up by 'setup.lua'
local iptool=require "iptool" 
local http_request = require "http_request"

local local_cidr = {
    "10.66.0.0/16",
    "10.67.0.0/16",
    "192.168.0.0/16",
    "172.31.0.0/16",
    "127.0.0.1"
}

 -- check if ip is local
 -- depends on $real_ip which setup by  setup.lua
function check_local_access()
    
    -- read ip from ngx.var.real_ip
    local ip = ngx.var.real_ip
    if (ip == nil or ip == '') then
        return
    end

    local is_local_ip = false
    for i = 1, #local_cidr do
      local is_in_cidr = iptool:pcall_check_ip_in_ipblock(ip, local_cidr[i],false)
      if is_in_cidr then
        is_local_ip = true
        break
      end
    end
    
    if not is_local_ip then
        ngx.exit(403);
        return
    end
end

check_local_access()