Ruan Bekker's Blog

From a Curious mind to Posts on Github

Nginx Basic Authentication With Source IP Whitelisting

Quick post on how to setup HTTP Basic Authentication and whitelist IP Based Sources to not get prompted for Authentication.

This could be useful for systems interacting with Nginx, so that they don’t have to provide authentication.

Dependencies:

Install nginx and the package required to create the auth file:

1
$ apt install nginx apache2-utils -y

Create the Password file:

1
$ htpasswd -c /etc/ngins/secrets admin

Configuration:

Create the site config:

1
2
$ rm -rf /etc/nginx/conf.d/*.conf
$ vim /etc/nginx/conf.d/default.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
    listen       80;
    server_name  localhost;

    location / {
        satisfy any;
        allow 127.0.0.1;
        deny all;

        auth_basic "restricted";
        auth_basic_user_file /etc/nginx/secrets;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Reload the Changes:

1
$ nginx -s reload

Testing:

Testing from our Whitelisted location (localhost):

1
2
curl -i http://127.0.0.1 
HTTP/1.1 200 OK

Testing from remote location:

1
2
3
4
5
$ curl -i http://localhost
HTTP/1.1 401 Unauthorized

$ curl -i http://admin:password@localhost
HTTP/1.1 200 OK

Comments