Introduction:
Securing your Nginx server is crucial to prevent unauthorized access and protect against malicious activities. Fail2Ban is a powerful and widely used intrusion prevention framework that can be utilized to enhance the security of your Nginx server. In this article, we will guide you through the process of setting up Fail2Ban on Rocky Linux 9 to protect your Nginx server from suspicious and malicious activities.
Step 1: Install Fail2Ban:
Before getting started, ensure that Fail2Ban is installed on your Rocky Linux 9 server. Open a terminal and execute the following command:
sudo dnf install fail2ban
Step 2: Configure Fail2Ban for Nginx:
Next, we need to configure Fail2Ban to monitor and protect the Nginx server. Create a new configuration file for Nginx by running the following command:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Open the jail.local
file in a text editor:
sudo nano /etc/fail2ban/jail.local
Scroll down to the [nginx]
section and make the following changes:
[nginx] enabled = true port = http,https filter = nginx[...] logpath = /var/log/nginx/access.log
Save and close the file.
Step 3: Create a Filter for Nginx:
We need to create a filter to specify the log patterns that Fail2Ban should monitor. Create a new filter file for Nginx by running the following command:
sudo nano /etc/fail2ban/filter.d/nginx.conf
Add the following content to the file:
[Definition] failregex = ^<HOST>.*"GET /.*HTTP.*" (401|403) ignoreregex =
Save and close the file.
Step 4: Restart Fail2Ban:
After configuring Fail2Ban for Nginx, restart the Fail2Ban service to apply the changes:
sudo systemctl restart fail2ban
Step 5: Monitor Fail2Ban Logs:
Fail2Ban logs its activity in the /var/log/fail2ban.log
file. Monitor this log file periodically to ensure that Fail2Ban is functioning correctly and protecting your Nginx server.
Step 6: Test Fail2Ban:
To test Fail2Ban, intentionally trigger a suspicious activity on your Nginx server, such as repeatedly accessing a protected resource with incorrect credentials. Fail2Ban should detect the suspicious activity and add the offender’s IP address to the firewall blacklist.
Step 7: Customize Fail2Ban Configuration (Optional):
You can further customize Fail2Ban’s behavior by modifying the configuration files in the /etc/fail2ban/
directory. For example, you can adjust the ban duration, email notifications, or add custom filters.
Conclusion:
By following the step-by-step guide outlined in this article, you have successfully set up Fail2Ban to protect your Nginx server on Rocky Linux 9. Fail2Ban helps in detecting and preventing suspicious activities by monitoring Nginx logs and dynamically adding IP addresses to the firewall blacklist. Regularly monitor the Fail2Ban logs to ensure its effectiveness and customize the configuration to suit your specific needs. By implementing Fail2Ban, you enhance the security of your Nginx server and safeguard it against potential threats and unauthorized access.