set

The 'set' directive assigns a value to a variable within the NGINX configuration context.

Syntaxset $variable value;
Defaultnone
Contextserver, location, if in server, if in location
Arguments2

Description

The 'set' directive in NGINX allows you to create or modify variables. This directive can be used in multiple contexts such as 'server', 'location', and within 'if' statements in those contexts. The syntax consists of two parameters: the first is the variable name (prefixed with a $ sign), and the second is the value you want to assign to that variable. For example, using 'set $my_var 'some_value';' will create a variable named 'my_var' with the value of 'some_value'. The value can be a string, a concatenation of other variables, or a value derived from NGINX's variables and settings.

The behavior of the 'set' directive ensures that the defined variable can be accessed anywhere in the specified context, including within nested configurations. It's important to note that once a variable is set, subsequent 'set' directives can alter its value, but these changes only take effect in the context where they are declared. Global variables can be defined in the http context, while local variables are scoped to locations or servers. Additionally, due to the lack of persistent storage, any modifications to variables made in one request will not affect another request, thereby ensuring request isolation.

Config Example

set $my_var 'hello world';

server {
    listen 80;
    location / {
        set $my_var 'example';
        return 200 "$my_var";
    }
}

Variables set in an 'if' context can have limited scope and may not function as expected outside of that context.

It's important to use the correct syntax with the '$' sign for variable names; forgetting it will cause the configuration to fail.

Ensure that variable names do not conflict with internal NGINX variables to avoid unexpected behavior.

← Back to all directives