0
0
NginxHow-ToBeginner · 3 min read

How to Block User Agent in Nginx: Simple Guide

To block a user agent in nginx, use the if directive inside a server or location block to check the $http_user_agent variable and return a 403 status code. For example, if ($http_user_agent ~* "BadBot") { return 403; } blocks requests from user agents matching "BadBot".
📐

Syntax

The basic syntax to block a user agent in nginx uses the if directive to test the $http_user_agent variable. If the user agent matches a pattern, you can return a 403 Forbidden response to block access.

  • if ($http_user_agent ~* "pattern"): Checks if the user agent matches the pattern (case-insensitive).
  • return 403;: Sends a 403 Forbidden response to block the request.
nginx
if ($http_user_agent ~* "pattern") {
    return 403;
}
💻

Example

This example blocks requests from user agents containing "BadBot" or "EvilScraper" by returning a 403 Forbidden status. Place this inside your server block in the nginx.conf or site config file.

nginx
server {
    listen 80;
    server_name example.com;

    if ($http_user_agent ~* "BadBot|EvilScraper") {
        return 403;
    }

    location / {
        root /var/www/html;
        index index.html;
    }
}
Output
When a request is made with a user agent containing "BadBot" or "EvilScraper", nginx responds with HTTP status 403 Forbidden and blocks access.
⚠️

Common Pitfalls

Common mistakes when blocking user agents in nginx include:

  • Using if directives outside server or location blocks, which causes configuration errors.
  • Not using the ~* operator for case-insensitive matching, causing some user agents to bypass the block.
  • Blocking too broadly with patterns that match legitimate user agents.
  • Forgetting to reload or restart nginx after changes.

Always test your configuration with nginx -t before reloading.

nginx
## Wrong way: case-sensitive match might miss some user agents
if ($http_user_agent ~ "BadBot") {
    return 403;
}

## Right way: case-insensitive match
if ($http_user_agent ~* "BadBot") {
    return 403;
}
📊

Quick Reference

Summary tips for blocking user agents in nginx:

  • Use if ($http_user_agent ~* "pattern") for case-insensitive matching.
  • Return 403 to deny access.
  • Place rules inside server or location blocks.
  • Test config with nginx -t before reload.
  • Reload nginx with systemctl reload nginx or equivalent.

Key Takeaways

Use the if directive with $http_user_agent to block specific user agents in nginx.
Always use case-insensitive matching with ~* to catch all variations.
Return a 403 status code to deny access to unwanted user agents.
Place blocking rules inside server or location blocks and test config before reloading.
Avoid overly broad patterns to prevent blocking legitimate users.