How to Block User Agent in NGINX


block user agent in nginx

Sometimes, you may have to block malicious user agents to your website, to protect your website from DDOS attacks, and unwanted traffic. Here’s how to block user agent in NGINX.

 

How to Block User Agent in NGINX

Here are the steps to block user agent in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Block User Agent

Let’s say you want to block user agent “Wget”. So simply add the following lines to your nginx.conf


if ($http_user_agent ~* (Wget) ) {
 return 403;
}

 

The ‘~*’ makes it a case insensitive match. If you want a case sensitive match


if ($http_user_agent ~ (Spider|Robot) ) {
 return 403;
}

 

If you want to block multiple user agents,


if ($http_user_agent ~ (Wget|Spider|Robot) ) {
 return 403;
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

Thats’s it! Now NGINX will automatically block the unwanted or malicious user agents that you have blocked on your website.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!