Essential Nginx Security Rules to Protect Your Website

nginx security rulesblock malicious botsprevent file downloadsnginx 444 status codedeny specific IP
Published·Modified·

Nginx (engine x) is a high-performance HTTP and reverse proxy server. Currently, a large portion of websites use Nginx as their web server. Although Nginx is very powerful, it cannot block malicious access by default. Xiaoz has compiled a list of common Nginx blocking rules to help you.

Before starting, ensure you are familiar with common Nginx commands (such as stopping and restarting) and how to troubleshoot Nginx error logs to avoid confusion if issues arise. Unless otherwise specified, the following commands should be added within the server block. Always back up your Nginx configuration before making changes, and reload Nginx after modification; otherwise, the changes will not take effect.

Prevent File Downloads

For example, if you export your website database to the site root for backup, it might be downloaded by others, leading to data loss. The following rules can prevent the download of common file types. Adjust them according to your actual needs.

location ~ \.(zip|rar|sql|bak|gz|7z)$ {
  return 444;
}

Block Uncommon Spiders (Crawlers)

If you frequently analyze your website logs, you may notice strange User Agents (UA) accessing your site frequently. These UAs are meaningless for search engine indexing and only increase server load. You can block them directly.

if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
     return 444;
}

Prohibit Script Execution in Specific Directories

For example, upload directories usually store static files. If program validation is not rigorous, trojans might be uploaded, leading to a hacked website. Modify the following rules to match your own directories and add script suffixes as needed.

# Prohibit PHP execution in uploads, templets, and data directories
location ~* ^/(uploads|templets|data)/.*.(php|php5)$ {
    return 444;
}

Block Specific IPs or IP Ranges

If your website is subjected to malicious spamming or CC attacks, analyze the log files to identify characteristic IPs and block them or their ranges.

# Block IP 192.168.5.23
deny 192.168.5.23;
# Block IP range 192.168.5.*
deny 192.168.5.0/24;

Other Notes

Once again, always back up your Nginx configuration before making changes, and reload Nginx after modification; otherwise, the changes will not take effect.

Most of the rules above return the 444 status code instead of 403. The 444 status code has a special meaning in Nginx: it directly terminates the connection from the server without returning any message to the client, making it more forceful than returning 403. If there are any deficiencies, please supplement and correct them.

Recommended Reading