How to Block Frequent Malicious IPs from Accessing Nginx with iptables
This guide shows how to install Nginx on a RedHat 6.5 system, simulate rapid requests from a malicious IP using ApacheBench, examine the access logs, and then block that IP permanently with an iptables rule or Nginx configuration, verifying the block with curl.
Experiment Environment
Operating system: RedHat 6.5. Target IPs: 172.16.1.100 (malicious) and 172.16.1.10 (Nginx server).
Install Nginx 1.11.2
ls
nginx-1.11.2.tar.gz
yum install gcc gcc-c++ make automake autoconf libtool pcre* zlib openssl openssl-devel
tar xf nginx-1.11.2.tar.gz
cd nginx-1.11.2
./configure
make
make installVerify Nginx Service
curl -I 172.16.1.100
HTTP/1.1 200 OK
Server: nginx/1.11.2
Date: Mon, 17 Aug 2020 09:36:29 GMT
Content-Type: text/html
Content-Length: 15
...Simulate Frequent Access
Use ApacheBench to generate ten requests with a concurrency level of one.
ab -c 1 -n 10 http://172.16.1.10/
...
Requests per second: 617.02 [#/sec] (mean)
Time per request: 1.621 ms (mean)
Transfer rate: 509.16 Kbytes/sec receivedCheck Access Log
tail /usr/local/nginx/logs/access.log
172.16.1.100 - - [26/Jul/2020:05:58:24 +0800] "GET / HTTP/1.0" 200 612 "-" "ApacheBench/2.3"
172.16.1.100 - - [26/Jul/2020:05:58:24 +0800] "GET / HTTP/1.0" 200 612 "-" "ApacheBench/2.3"
... (repeated 10 times)Block IP with iptables
iptables -I INPUT -s 172.16.1.100 -p tcp --dport 80 -j DROPVerification that the IP is blocked:
curl 172.16.1.10
curl: (7) Failed connect to 172.16.1.10:80; Connection timed outAlternative: Nginx deny directive
Add a deny rule to the nginx.conf file inside the appropriate server block: deny 172.16.1.100; Reload Nginx to apply the change ( nginx -s reload). After reloading, the malicious IP receives HTTP 403 Forbidden:
curl -I 172.16.1.10
HTTP/1.1 403 Forbidden
Server: nginx/1.11.2
Date: Sat, 25 Jul 2020 23:12:06 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-aliveThe following snippet illustrates the deny configuration in nginx.conf:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
