Blocking IPs with Nginx

 

Overview

A custom configuration file lets you control IP access to your website running on an Nginx server, 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:

How do I create the configuration file?

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

DreamPress plans do not support changes to the local Nginx configuration directory, meaning configuration adjustments cannot be made directly by the user.

If you need to customize the access.conf file, please contact support for assistance.

  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.

How do I block an IP from my 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;
}

How do I 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;
}

How do I allow only a single IP to access my 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; 
    }

How do I combine 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?