Skip to content

Instantly share code, notes, and snippets.

@net1
Forked from rm3nchaca/example_host.conf
Created December 9, 2022 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save net1/595e8aefdb61aa500cf91eb0b7482dd6 to your computer and use it in GitHub Desktop.
Save net1/595e8aefdb61aa500cf91eb0b7482dd6 to your computer and use it in GitHub Desktop.
Simple script for blocking attacker bots with nginx and a lua script
server {
listen 80;
server_name example.com;
root /www/example;
access_by_lua 'denyip()'; #check error counter
error_page 400 404 405 406 = /404.html;
location = /404.html {
set $inc 1; #this is useful for blocking website scanners
set_by_lua $err 'incerror()' $inc;
internal;
}
error_page 403 500 502 503 504 = /500.html;
location = /500.html {
set $inc 5; #Modsecury send 403 errors, so here we can add more "weight" to this errors
set_by_lua $err 'incerror()' $inc;
internal;
}
.
.
.
location / {
index index.html;
}
}
--init_blockip.lua
local match = string.match
local ngxmatch=ngx.re.match
errorCount = 50 --how many errors to permit
errorSeconds = 60 -- in an interval of n seconds
blockSeconds = 300 --block the ip
function getClientIp()
IP = ngx.req.get_headers()["X-Real-IP"]
if IP == nil then
IP = ngx.var.remote_addr
end
if IP == nil then
IP = "unknown"
end
return IP
end
--verify counter
function denyip()
local uri=ngx.var.uri
local token = getClientIp()
local limit = ngx.shared.limit
local req,_=limit:get(token)
if req then
if req > errorCount then
limit:set(token,req,blockSeconds)
ngx.log(ngx.STDERR, 'NGINX BLOCK IP:', token, ', errors: ', req) --log the ip blocked
ngx.status = ngx.HTTP_MOVED_TEMPORARILY
ngx.exit(ngx.HTTP_OK)
return true
end
end
return false
end
--increment the counter on error
function incerror()
local uri=ngx.var.uri
local token = getClientIp()
local limit = ngx.shared.limit
local req,_=limit:get(token)
local num = tonumber(ngx.arg[1]) or 1
if req then
limit:incr(token,num)
else
limit:set(token,num,errorSeconds)
end
return false
end
.
.
.
.
.
http {
include mime.types;
default_type application/octet-stream;
server_tokens off;
lua_package_path "/etc/nginx/lua/?.lua"; #where your lua script are located
lua_shared_dict limit 10m;
init_by_lua_file /etc/nginx/lua/init_blockip.lua; #the lua script
.
.
.
.
include /etc/nginx/conf.d/*.conf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment