Blocking IPs with Nginx

 

Overview

This article explains how to create a custom configuration file to control IP access to your website running on an Nginx server. This is accomplished using the Nginx location module.

Users whose IP address is blocked will then see a 403 Forbidden error when visiting your website.

Prerequisites

This article assumes you have completed the following steps:

Creating the configuration file

The following steps create a file named access.conf, which is used to add the code examples in this article.

  1. View the Nginx configuration file locations article to create your local /nginx/example.com directory.
  2. Change into this directory:
    [server]$ cd ~/nginx/example.com
  3. Create a file named access.conf.
  4. Add code from one of the examples below.
  5. Reload Nginx for the changes to take effect.

Code examples

The following examples can be added to your access.conf file as needed.

To view the IP addresses that have visited your website, check your site's access.log file.

Block an IP from your website

The following code blocks the IP address of 1.2.3.4 from accessing your website.

  • The forward slash / indicates your entire website.
  • The deny directive controls what is blocked.
location / {
  deny 1.2.3.4;
}

Block an IP from a subdirectory

The following code blocks the IP address of 1.2.3.4 from accessing a subdirectory on your site named /blog:

location /blog/ {
  deny 1.2.3.4;
}

Allow only a single IP to access your website

The following code allows the single IP address of 1.2.3.4 to access your website while blocking all others. This could be useful if you're building your website and do not want anyone to view it while it's being worked on.

The deny all; line must appear after all IP addresses in the list.

If it is the first line, ALL IP addresses will be blocked.

location / {
  allow 1.2.3.4;
  deny all;
}

Multiple rules

You can also combine multiple rules. The following example allows a single IP address to access the /blog subdirectory while blocking all others from the primary website URL:

location /blog {
  allow 1.2.3.4;
  deny all;
}

location / {
  deny all;
}

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?