Conditional Blocking in nginx based on User Agent


#1

This tutorial was requested by @Abhijeet

It is a very simple process to block a specific user agent or a group of user agents (or to allow them) in nginx if you’re familiar with how the conf files work.

For this process to work, You have to modify the nginx.conf file. This is usually located into the working directory of nginx. in our case, it’s /etc/nginx if you’ve built nginx from source then this can be different.

first step is to open the nginx.conf file in nano:

sudo nano /etc/nginx/nginx.conf 

Then locate the section that says HTTP

Then add the following block at the very bottom of the http block (before the } )

if ($http_user_agent ~* (Windows 95|Windows 98|wget|curl|libwww-perl) ) {
return 403;
}

Here we’re blocking Windows 95, 98, Wget, curl and perl useragents.
You can find a list of most popular browser agents here:

And add the browser agent string to the block in a pipe-separated list |

If you have any questions, make sure to leave them below.


#2

Thankyou for this :slight_smile: