Notes

Nginx Auth With IP Whitelists

June 29, 2019

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.

# 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>;

    ...
}