Skip to content

Instantly share code, notes, and snippets.

@philipjewell
Last active August 20, 2017 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipjewell/60a6fde582d172b5de44a1755577400a to your computer and use it in GitHub Desktop.
Save philipjewell/60a6fde582d172b5de44a1755577400a to your computer and use it in GitHub Desktop.
Allow geo restricting with nginx

For this example, using multiple nginx conditions we're leveraging MaxMind's GeoIP. Here we are only allowing traffic from Brazil and the IP address of: 192.171.XXX.XXX (our local IP address). You can find your local IP address using websites like whatismyipaddress.com or Googling "what is my ip address" should return your local IP. You can find the list of country codes here, as well as use Regex in order to pipe together IP addresses and/or countries.

Listed below are a few if statements we're placing in the nginx config of the site. This will allow us to set values and determine what the response will be depending on what those values equal:

set $allowed_geo 0;
set $allowed_ipaddr 0;

if ($geoip_country_code !~* BR) {
set $allowed_geo 1;
}
if ($remote_addr !~* "192.171.XXX.XXX") {
set $allowed_ipaddr 1;
}
if ("$allowed_geo:$allowed_ipaddr" = "1:1") {
return 403;
}

This can also be written out in this way:

if ($geoip_country_code !~* BR) {
set $test A;
}
if ($remote_addr !~* "192.171.XXX.XXX") {
set $test "${test}B";
}
if ($test = AB) {
return 403;
}

This rule allows me to see from my local machine and then was able to confirm that it was working in Brazil by using GeoPeeker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment