Перейти к содержанию

Examples

Restrict Access by Country

You may want to restrict access to your website based on the visitor's country. This can be useful for compliance with local laws or to prevent unwanted traffic.

load_module modules/ngx_http_geoip2_module.so;

http {
    geoip2 /etc/maxmind-country.mmdb {
        $geoip2_data_country_code default=US source=$remote_addr country iso_code;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            if ($geoip2_data_country_code = "US") {
                return 403;
            }
            proxy_pass http://backend;
        }
    }
}

Caveat: Ensure your GeoIP database is up-to-date to avoid incorrect blocking.

Serve Different Content Based on City

You might want to serve different content or redirect users based on their city. This can be useful for localizing content or services.

load_module modules/ngx_http_geoip2_module.so;

http {
    geoip2 /etc/maxmind-city.mmdb {
        $geoip2_data_city_name default=London city names en;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            if ($geoip2_data_city_name = "New York") {
                return 302 https://ny.example.com;
            }
            proxy_pass http://backend;
        }
    }
}

Caveat: City-level data may not be as accurate as country-level data.

Log Visitor's Country Code

Logging the country code of visitors can help in analyzing traffic patterns and making informed business decisions.

load_module modules/ngx_http_geoip2_module.so;

http {
    geoip2 /etc/maxmind-country.mmdb {
        $geoip2_data_country_code default=US source=$remote_addr country iso_code;
    }

    log_format custom '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" '
                      '"$geoip2_data_country_code"';

    access_log /var/log/nginx/access.log custom;

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://backend;
        }
    }
}

Caveat: Ensure log files are rotated regularly to prevent disk space issues.

Use GeoIP2 with Stream Module

You can use the GeoIP2 module with the stream module to apply country-based rules to TCP/UDP traffic.

load_module modules/ngx_stream_geoip2_module.so;

stream {
    geoip2 /etc/maxmind-country.mmdb {
        $geoip2_data_country_code default=US source=$remote_addr country iso_code;
    }

    server {
        listen 12345;

        if ($geoip2_data_country_code = "CN") {
            return 403;
        }

        proxy_pass backend:12345;
    }
}

Caveat: Stream module does not support HTTP-specific features like headers.

See also

For troubleshooting tips and common issues, refer to troubleshooting.md.