How to block requests from specific IP address in Nginx

Ashok Raja T
Technology Specialist
October 21, 2019
Rate this article
Views    16499

You may end up to situations where you may have to block requests from specific ip addresses to your website. If you are running your web application with Nginx, then this is for you. There are multiple configuration options available in Nginx to block IP address. Let see couple of options in this article.

Block requests from specific or range of IP Address

The easiest and quickest option is to block an IP is to call the deny command with IP Address. This blocks all requests from that specific address. Instead of IP address, you can also specify the IP Range with “deny” command.

location / {
   deny 127.0.0.1; # Individual IP Address
   deny 1.2.3.0/24; # IP Address range
}

The above code snippet is a standard code sample that you can see everywhere that talks about blocking IP Address in Nginx. But in reality, you may end up blocking huge list of IP Addresses and the above way of approach will become too complicated too soon. In such scenario, the below approach of maintaining a black list would be handy.

Blocking huge list of IP Addresses

1. Create a new file called banned-ip.conf inside the nginx snippets folder. Usually, “snippets” folder would be located at the default location where “nginx.conf” file is located. In Ubuntu, the location would be “/etc/nginx/snippets”

2. Add the Ip addresses that you wish to block to that file in the bellow format.

geo $bad_ip {
    default 0;
    202.72.213.218 1;
    another_ip 1;
    another_ip 1;
    ...
    ...
}

In the above code, default should be always 0 to allow all requests. All Ip’s that you wish to block should have a number other than zero.

3. Inject the above file in the “http” block of nginx.conf so that it can be referred in any config file.

include /etc/nginx/snippets/banned-ip.conf;

4. Now, in your application level config file (usually located in “sites-available” folder) add the below code segment to the top of “server” block to validate the in-coming requests.

location / {
    if ($bad_ip) {
        return 444;
    }
}
With deny method, usually a 403 Unauthorised http status would be sent to the requesting client. Here in the above method, we close the connection with 444 http status without sending any response.

5. Reload the nginx configuration to make the changes effective by executing the command

nginx -s reload

That’s it. Now, Nginx will stop all requests from the Ip Address that are referred in banned-ip.conf

If you are trying to protect a WordPress site running behind nginx, you can also refer my earlier article for more details.

Subscribe To Our Newsletter
Loading

Leave a comment