Distributed Denial of Service (DDoS) attacks pose a significant threat to web servers, causing downtime and performance issues. Nginx offers robust features to mitigate DDoS attacks. In this guide, we’ll walk through the process of configuring DDoS protection in Nginx, providing command examples for each step.
Step 1: Install Nginx
Before configuring DDoS protection, ensure Nginx is installed on your server. Use the package manager specific to your operating system. For example, on Ubuntu, run:
sudo apt-get update
sudo apt-get install nginx
Step 2: Update Nginx Configuration
Open the Nginx configuration file in a text editor. This file is commonly located at /etc/nginx/nginx.conf
or /etc/nginx/sites-available/default
. Add the following lines to limit the number of connections per IP:
http {
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 10;
}
These lines create a connection limit per IP, preventing a single IP from overwhelming the server with too many connections.
Step 3: Set Up Rate Limiting
Implementing rate limiting helps control the number of requests from a single IP address. Add the following lines to your Nginx configuration:
http {
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
limit_req zone=req_limit_per_ip burst=10;
}
These settings restrict the request rate to 5 requests per second per IP, with a burst limit of 10 requests.
Step 4: Enable Connection Timeout
To protect against slowloris attacks, set a connection timeout. This prevents attackers from keeping connections open for an extended period. Add the following line to your configuration:
http {
keepalive_timeout 5;
}
This configuration ensures that connections are closed if there is no activity within 5 seconds.
Step 5: Implement IP Whitelisting
If you have known trusted IP addresses, consider whitelisting them to allow unrestricted access. Add the following lines to your configuration:
http {
allow 192.168.1.1;
deny all;
}
Replace 192.168.1.1
with your trusted IP address. This configuration permits access only from the specified IP.
Step 6: Test Configuration Changes
After making the configuration changes, it’s crucial to test them to ensure they don’t negatively impact your website’s functionality. Use the following command to check for syntax errors:
sudo nginx -t
If the test is successful, restart Nginx to apply the changes:
sudo service nginx restart
Conclusion
Configuring DDoS protection in Nginx is essential to safeguard your web server against malicious attacks. Following the above steps and using the provided command examples can enhance the security of your Nginx server and mitigate the impact of DDoS attacks.