Search code examples
nginxbasic-authentication

Requiring basic auth depending on the origin of the request (filtering by country with geo module)


Is there a way I can require basic auth depending on the origin of the request, filtering by countries? My goal is to be able to always require basic auth, except when the request is coming from X, Y or Z countries.


Solution

  • This answer is under the assumption that you already have the module installed and working, there are tons of good guides out there to install it, so I'll skip it.

    You can map the geoIP with:

    geoip_country /path/to/GeoIP/GeoIP.dat;
    map $geoip_country_code $not_auth_required {
        default no;
        ZZ yes;
        YY yes;
        XX yes;
    }
    

    And then set a basic auth for everyone except those:

    server {
        listen 80;
        root   /foo/bar/baz;
        auth_basic           “Wrong Country";
        auth_basic_user_file /etc/nginx/.htpasswd; #typical user:$hash auth.
    
        if ($not_auth_require = yes) {
            auth_basic off;
        }
    
    
        location / {
             #do things
        }
    }
    

    In theory this logic should do the trick, as you need a whitelist, and not a blacklist. I hope I helped