Common Nginx Blocking Rules to Make Your Website More Secure

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.

Preventing file downloads

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;
}

Blocking uncommon spiders (crawlers)

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;
}

Disabling script execution in a directory

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;
}

Blocking a specific IP or IP range

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;

Other notes

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.

Recommended Reading


Comments