Blocking IPs with Nginx

Overview

Nginx servers allow you to control IP access to your website by creating a custom configuration file. You can view the IP addresses that have visited your website by viewing your access.log file. Users whose IP address is blocked will see a 403 Forbidden error when visiting your website.

This article explains how to create this file and includes code examples you can add to it.

View the following page for further details about the Nginx location module:

Blocking IPs

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

  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

Block an IP from your website

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

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;
}

Only allow a single IP to access your website

The following code allows a single IP address 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 website:

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?