Publish: 2018-09-12 | Modify: 2018-09-12
Nginx (engine x) is a high-performance HTTP and reverse proxy server. Currently, a large number of websites use Nginx as their web server. Although Nginx is very powerful, it does not block malicious access by default. Xiaoz has compiled a list of commonly used Nginx blocking rules, hoping to help you.
Before we begin, it is assumed that you are familiar with common Nginx commands (such as stopping, restarting, etc.) and troubleshooting Nginx error logs, so as not to be at a loss when problems occur. Unless otherwise specified, the following commands should be added to the server
section. Be sure to backup the Nginx configuration before modifying it. Once modified, you need to reload Nginx for the changes to take effect.
For example, if you export the website database to the site's root directory for backup, it is likely to be downloaded by others, which could lead to data loss. The following rules can prevent some common files from being downloaded. Add or remove them according to your actual situation.
location ~ \.(zip|rar|sql|bak|gz|7z)$ {
return 444;
}
If you often analyze website logs, you will find that some strange user agents (UA) frequently access the website, and these UAs have no meaningful contribution to the website's indexing. Instead, they increase the server's load. You can directly block them.
if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
return 444;
}
For example, the website upload directory usually contains only static files. If a malicious program is uploaded due to lax program validation, the website may be compromised. Please modify the following rules according to your own situation. You can also add the script extensions you want to block.
# Disable PHP execution in uploads|templets|data directories
location ~* ^/(uploads|templets|data)/.*.(php|php5)$ {
return 444;
}
If the website is subjected to malicious flooding or CC attacks, you can analyze the characteristic IPs from the website logs and block them.
# Block the IP 192.168.5.23
deny 192.168.5.23;
# Block the IP range 192.168.5.*
deny 192.168.5.0/24;
Again, be sure to backup the Nginx configuration before modifying it. Once modified, you need to reload Nginx for the changes to take effect.
Most of the rules above return a 444
status code instead of 403
because the 444 status code has a special meaning in Nginx. The 444 status code terminates the connection directly from the server without returning any message to the client, making it more forceful than returning 403. If there are any shortcomings, please provide additional information and corrections.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.