label

Defines global key-value labels for access in NGINX configuration and request processing.

Syntaxlabel key value;
Defaultnone
Contexthttp
Arguments2

Description

The label directive in NGINX allows the user to define global key-value pairs that can be accessed throughout the NGINX configuration using variables. Each label is assigned a unique key and value, where the key can only consist of letters, numbers, and underscores. Importantly, labels cannot be redefined once created. This directive operates within the http context, meaning it applies globally across the server or location blocks defined within the configuration. The values assigned to labels exclude special characters such as & and = to maintain proper syntax and functionality within NGINX's internal variable evaluations.

When configured, defined labels can be retrieved using variable syntax, such as $label_key_name, where key_name corresponds to the specific label's identifier. This makes it convenient for use in various places within the configuration, like logging, headers, or dynamic response handling. Moreover, another variable, $labels, aggregates all defined labels into a single string formatted as key1=value1&key2=value2, providing a simpler way to include all related information in responses. Under the hood, label storage is managed by a hash table, the configuration of which can be fine-tuned through additional directives to optimize performance as necessary.

Config Example

http {
    label environment production;
    label cluster_id my_cluster_id;
    label server_region us-east-1;
    label server_id my_server_id;

    server {
        listen 80;
        server_name example.com;
        location / {
            add_header Server-Id $label_server_id;
            add_header Cluster-Id $label_cluster_id;
            add_header All-Labels $labels;
            return 204;
        }
    }
}

Labels cannot contain special characters like '&' and '=' in their values.

The same key cannot be defined multiple times; doing so will result in an error during configuration parsing.

Label keys must begin with a letter and can only contain letters, numbers, and underscores.

← Back to all directives