DEV Community

Cover image for Restricting Access by Geographical Location using NGINX with Helm
Pascal Gillet
Pascal Gillet

Posted on • Updated on

Restricting Access by Geographical Location using NGINX with Helm

This article explains how you can restrict content distribution to a particular country from services in your Kubernetes cluster, using the GeoIP2 dynamic module.


  • Install NGINX Ingress Controller in your Kubernetes cluster using Helm.

Getting the GeoLite2 databases from MaxMind

The MaxMind company provides the GeoLite2 free IP geolocation databases. You need to create an account on the MaxMind website and generate a license key.

Configuring the NGINX Ingress Controller

Override the NGINX Helm chart with the following values:

  # Maxmind license key to download GeoLite2 Databases
  maxmindLicenseKey: ""
    # GeoLite2 Databases to download (default "GeoLite2-City,GeoLite2-ASN")
    maxmind-edition-ids: GeoLite2-Country
    # Preserve source IP...
    externalTrafficPolicy: Local
    # ...Which is only supported if we enable the v2 proxy protocol for the OVH load balancer (specific to OVH Cloud provider)
    annotations: "v2"
    use-proxy-protocol: "true"
    # Enable Ingress to parse and add -snippet annotations/directives
    allow-snippet-annotations: "true"
    # Enable geoip2 module
    use-geoip: "false"
    use-geoip2: "true"
    # Configure access by geographical location.
    # Here, we create a variable $allowed_country whose values 
    # depend on values of GeoIP2 variable $geoip2_country_code,
    # which lists all ISO 3166 country codes.
    # Map directives are only allowed at Ingress Controller level.
    http-snippet: |
      map $geoip2_country_code $allowed_country {
        default no;
        FR yes;
        US yes;
Enter fullscreen mode Exit fullscreen mode

Example Ingress

A minimal Ingress resource example:

kind: Ingress
  name: minimal-ingress
  annotations: /
    # Restrict access by geographical location |
      if ($allowed_country = no) {
        return 451;
  ingressClassName: nginx-example
  - http:
      - path: /testpath
        pathType: Prefix
            name: test
              number: 80
Enter fullscreen mode Exit fullscreen mode

Note: The HTTP status code 451 was chosen as a reference to the novel
"Fahrenheit 451".


Top comments (1)

michael_cameroon_5cbe537b profile image
Michael Cameroon

This is am interesting article. Apart from using MaxMind, you can also use other databases such as IP2Location in NGINX, as shown in the article below.