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:
- Upgraded to a VPS or Dedicated hosting plan
- Changed your server to run Nginx.
- Created a Shell user and are able to log into your server via SSH.
Creating the configuration file
The following steps create a file named access.conf, which is used to add the code examples in this article.
- View the Nginx configuration file locations article to create your local /nginx/example.com directory.
- Change into this directory:
[server]$ cd ~/nginx/example.com
- Create a file named access.conf.
- Add code from one of the examples below.
- 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; }