首页 > 代码库 > nginx + lua + redis 防黑IP

nginx + lua + redis 防黑IP

lua脚本

local redis = require "resty.redis"
local red = redis.new()
red.connect(red, ‘127.0.0.1‘, ‘6379‘)

local myIP = ngx.req.get_headers()["$remote_addr"]

if myIP == nil then
   myIP = ngx.req.get_headers()["x_forwarded_for"]
end
if myIP == nil then
   myIP = ngx.var.remote_addr
end

local hasIP = red:sismember(‘black.ip‘,myIP)
 
 if hasIP==1  then
     return  ngx.exec("@ErrorPage")
 else
     return ngx.exec("@mysite")
 end

 

nginx配置

    server {
        listen       80;
        server_name  localhost;

        location / {
     
    access_by_lua_file /var/openresty/nginx/conf/my_access_limit.lua;
        }

    location @ErrorPage {
    root    html/ErrorPage;
    index  index.html index.htm;

}
   location @mysite {
        root    html/mysite;
        index  index.html index.htm;
}
}

 

END!

nginx + lua + redis 防黑IP