Blocking Malicious Traffic
Introduction
Welcome to the third lesson of Securing Your NGINX Server! In our previous lessons, we learned how to protect resources using authentication and how to control request rates with rate limiting. Today, we're adding another essential layer to your security toolkit: blocking malicious traffic based on IP addresses and user agent signatures.
This lesson focuses on identifying and rejecting suspicious clients before they can interact with your application. You'll learn how to block specific IP addresses, deny entire ranges using CIDR notation, and filter out known malicious bots and scanning tools. By the end, you'll have practical techniques for keeping unwanted traffic away from your server.
Recognizing Threats at the Network Layer
While authentication and rate limiting protect against legitimate users acting improperly, some threats come from sources that should never reach your application at all. Consider these real-world scenarios:
Attackers often probe servers from known malicious IP ranges, searching for vulnerabilities to exploit. Automated tools like sqlmap attempt SQL injection attacks, while various scanners probe for security weaknesses. These tools frequently identify themselves through their user agent strings, making them detectable and blockable.
The advantage of blocking at this level is efficiency: NGINX can reject malicious requests immediately, before they consume server resources or reach your application code. This early rejection protects both your server's performance and your application's security.
Blocking Specific IP Addresses
The simplest form of IP blocking uses the deny directive to reject traffic from a specific address. Let's start with a basic configuration:
This configuration blocks the IP address 198.51.100.23 while permitting all other clients. The deny directive appears first, followed by allow all, which permits any address not explicitly denied. The order here matters significantly: NGINX processes these directives sequentially, stopping at the first match.
When a request passes the IP checks, try_files forwards it to the named location @root, which handles the actual response. This separation keeps your access control logic distinct from your response handling.
