Whitelist IPs in Nginx

I want to whitelist my clients IP addresses (and my office IPs) to allow them to view a site, while the rest of the world will be redirected to another site, using Nginx. My Nginx server is behind a load balancer.

Using the geo module I am able to do this rather easily. By default, geo will use $remote_addr for the IP address. However, because our server is behind a load balancer this will not work, as it would always be the IP of the load balancer. You can pass in a parameter to geo to specify where it should get the IP value. In this case, we want to get the IP from

$http_x_forwarded_for.

geo $http_x_forwarded_for $redirect_ips {
  default     1;
  1.2.3.4/32  0;
  1.2.3.5/32  0;
  9.8.7.6/32  0;
}

What this is doing is assigning the variable $redirect_ips the value after the IP address. So, if my IP is 1.2.3.4, $redirect_ips will have a value of 0, or false. If my ip is not matched, it will get the default value of 1, or true;

Ok, with that, my server directive now looks like:

# Site that is not quite ready for the public to see, but we want to test on prod
server {
    listen 80;
    server_name es.example.com;

    if ( $redirect_ips ) {
        return 302 https://us.example.com$request_uri;
    }

    # the rest of my server directive goes below this line...
    # removed for clarity in this example.

}