Geo dynamic upstream with nginx

I recently had to setup nginx as load balancer at work. Due to the reason that one of our customer is in China, we have to add few China servers to our load balancer and route everything from China to those instead.

Turn out it’s quite easy to do it with nginx and geo package. You will need nginx-full or compile nginx yourself with geo package.

After setting nginx with geoip. Create a new configuration in site-available, symlink to site-enabled to enable it.

The content of the fie should look like this

upstream first_upstream  {
    ip_hash; # for sticky session
    server <first-01>;
    server <first-02>;

upstream second_upstream {
    server <second-01>;
    server <second-02>;

map $geoip_country_code $preferred_upstream {
    default first_upstream;
    CN second_upstream; # use second_upstream for those from China (CN)

server {
    location / {
        proxy_pass http://$preferred_upstream/;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;