You can block specific user agents in Nginx by using the if
directive in the server block. Here’s an example:
server {
...
if ($http_user_agent ~* (bad-agent1|bad-agent2)) {
return 403;
}
...
}
This example blocks requests from user agents that contain the string “bad-agent1” or “bad-agent2”. The return
statement returns a HTTP status code of 403 (Forbidden) to the client, effectively blocking the request.
You can replace (bad-agent1|bad-agent2)
with a regular expression that matches the user agents you want to block. For example, to block all requests from Internet Explorer, you could use (MSIE|Trident)
.
After making changes to the Nginx configuration, remember to test the configuration and reload Nginx for the changes to take effect.