Table of Contents
Introduction
Some examples of securing nginx locations with IP address checking, and HTTP basic authentication.
IP Address Checking
How do we lock down access to locations by IP address using Nginx?
The Internal Network
There may be a location we want to be exposed only to the internal network. Using the allow and deny directives:
allow 192.168.1.0/24;
deny all;
These directives will allow any IP in the 192.168.1.x access to the location. /24 is the same as a 255.255.255.0 network mask, it means the first 24 bits denote the subnet. This form is called CIDR notation.
A Specific IP
If there is a specific IP we wish to grant access, we can add another allow:
allow 192.168.1.0/24;
allow 127.0.0.1;
deny all;
In this case we’re also granting access permission to loopback requests.
Password Protection
How do we require people to enter a username and password before accessing a location?
Password Checking
We can add HTTP basic password protection using htpasswd files. The following is one approach to do this for a location:
auth_basic "Restricted Area";
auth_basic_user_file /path/to/htpasswd
To create /path/to/htpasswd use the htpasswd command e.g. htpasswd -c /path/to/htpasswd <username>.
Password Protection AND IP checking
Access can also be locked down using both IP checking and htpasswd. The example will only allow requests from the internal network, if they also provide the correct username and password.
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /path/to/htpasswd
Password Protection OR IP checking
Maybe you want to allow access to the internal network, but for all other requests require a username and password. This can be achieved using the satisfy directive like so:
satisfy: any;
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /path/to/htpasswd