geo

The `geo` directive in NGINX defines a variable that can be set based on client IP addresses or other geographic locations.

Syntaxgeo $variable { default value; range1 value1; range2 value2; ... }
Defaultnone
Contexthttp
Argumentsblock (1-2)

Description

The geo directive is utilized to create a mapping of client IP addresses to variables that can be used in various NGINX configurations. It is especially useful for configuring access control and managing request routing based on geographical location. This directive can define both IPv4 and IPv6 addresses and can be nested within the http context. Each mapping rule consists of an address (or range) and an optional variable that can either contain a value (such as '1' or '0' for allowing or denying access) or be set to 'default' for unmatched addresses.

Within the geo block, you can specify individual IP addresses, CIDR notations, or geographic ranges. NGINX will evaluate the client's IP address against these rules in the order they are defined. If a match is found, NGINX will set the specified variable accordingly. If an address is not matched by any rule, the value set by the default directive will be applied. This makes geo a powerful tool for creating dynamic configurations that respond to different client IPs, whether for load balancing, access control, or application configuration.

It is important to understand that the geo directive must be defined in the http block, and it does not take other associated directives directly within it, which can lead to confusion in complex NGINX configurations. Additionally, this directive operates at the HTTP layer and fundamentally depends on the networking details of incoming requests, necessitating proper use based on the expected characteristics of client requests.

Config Example

geo $remote_addr {
    default 0;
    192.168.1.0/24 1;
    10.0.0.0/8 2;
}

Make sure the geo block is inside the http context; placement elsewhere will lead to errors.

When using CIDR notation, ensure the syntax is correct to avoid unintended matches.

Remember that the order of definitions matters; the first match found will determine the value of the variable.

← Back to all directives