albertyw/albertyw.com

View on GitHub
app/notes/20190629-2214.md

Summary

Maintainability
Test Coverage
Nginx Auth With IP Whitelists

nginx-auth-ip-whitelists

1561846449

I was looking into a way to configure Nginx to require basic HTTP authentication
but to skip authentication for specific IP addresses.  I was also running Nginx
behind Cloudflare, which obscures the caller IP address.  The normal way of
reading IP addresses wouldn't work, so I had to switch up the IP address whitelist
to read from a Cloudflare-set header `CF-Connecting-IP`.

```nginx
# Create a map of IP addresses to auth configuration
map $http_cf_connecting_ip $auth {
    # Whitelisted ip address has auth off
    "<Whitelisted IP Address>"  "off";
    # Otherwise, auth is enabled
    default                     "Authentication Required";
}

server {
    ...

    # Enable HTTP authentication
    auth_basic           $auth;
    # Set a file with username/password data
    auth_basic_user_file <path to auth file>;

    ...
}
```