nginx map, geo

By | September 30, 2020
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

below one will handle or not handle the request based on original country. geoip_country_code is a variable provided by nginx to tell the country of the IP.

# Allowed countries
#
map $geoip_country_code $allowed_country {
    default no;
    country_code_1 yes;
    country_code_2 yes;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # Disallow access based on GeoIP
    if ($allowed_country = no) {
        return 444;
    }

}

below one, it returns site content based on the host name. $host is a variable provided by nginx.

map $host $site_content {
  default "public";

  "grahamweldon.com" "grahamweldon";
  "slavitica.net" "slavitica";
}

http {
  [ ... ]

  server {
    listen 80 default_server;
    server_name _;
    location / {
      root /usr/local/websites/$site_content;
      try_files $uri index.html =404;
    }
  }
  
}

geo module is similar to map. But it can do complex mapping for IP. Below one store log based on client IP address.

geo $remote_addr $log_request {
  ranges;
  default 1;

  10.0.0.0-10.2.0.12 0;
  10.2.8.103-10.2.8.254 0;
}

location {
  root /some/path;
  access_log /var/log/access.log combined if=$log_request;
}

Category: web