Question

Exception for IP in Basic Auth on NGINX

Posted August 19, 2021 148 views
NginxSecurity

Hi, do you know a working way to set an exception for an IP address in NGINX? I tried with satisfy and @geolocation but it doesn’t work. I am using version 1.18.0.

Regards

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Hi @MichalGiza,

All you need to do is allow the IP inside the server block which you have your basic auth in.

Combining Basic Authentication with Access Restriction by IP Address
HTTP basic authentication can be effectively combined with access restriction by IP address. You can implement at least two scenarios:

a user must be both authenticated and have a valid IP address
a user must be either authenticated, or have a valid IP address
Allow or deny access from particular IP addresses with the allow and deny directives:

location /api {
    #...
    deny  192.168.1.2;
    allow 192.168.1.1/24;
    allow 127.0.0.1;
    deny  all;
}

Access will be granted only for the 192.168.1.1/24 network excluding the 192.168.1.2 address. Note that the allow and deny directives will be applied in the order they are defined.

Combine restriction by IP and HTTP authentication with the satisfy directive. If you set the directive to to all, access is granted if a client satisfies both conditions. If you set the directive to any, access is granted if a client satisfies at least one condition:

location /api {
    #...
    satisfy all;    

    deny  192.168.1.2;
    allow 192.168.1.1/24;
    allow 127.0.0.1;
    deny  all;

    auth_basic           "Administrator’s Area";
    auth_basic_user_file conf/htpasswd;
}

Regards,
KFSys

  • Hi, thank you. I tested the method given by you, but it was not effective. After many attempts, it turned out that my new way works:

    geo $allow {
        default 0;
        IP_address 1;
    }
    

    and below server:

    set $auth "Authorization required";
            if ($allow = 1) {
              set $auth off;
            }
    
            auth_basic $auth;
            auth_basic_user_file "/path/to/file";
    

    Regards