var
The `var` directive allows dynamic variable assignment in NGINX using predefined functions.
Description
The var directive in NGINX is used to dynamically create and assign values to variables based on the results of predefined functions. This directive can be utilized in different contexts, including http, server, and location, allowing for flexible and contextual variable scoping. The directive's syntax is structured as follows: var $variable_name function [-i] args... [if=condition], where variable_name is the name of the variable to be defined, function specifies the predefined operation to be applied, and args can consist of additional parameters relevant to the function.
A key feature of the var directive is that it calculates the variable's value each time it is referenced, instead of caching it. As such, any changes in the request or context can cause the variable to reflect updated values accordingly. The optional -i parameter indicates that the function should ignore case sensitivity when processing string functions. The resultant variable may also depend on the evaluation of conditional expressions, allowing for more complex logic to direct variable values dynamically.
However, it’s crucial to note that variables defined with the var directive cannot be defined simultaneously with the map or geo directives, ensuring that potential conflicts in variable assignment are avoided. Using the set directive can override previously defined variables, providing additional control over variable definitions within server configurations.
Config Example
server {
listen 127.0.0.1:8080;
server_name localhost;
location / {
var $new_var set $scheme://$host$request_uri;
}
}Variables defined with var cannot be used simultaneously with map or geo directives.
Check that the function name and parameters are correctly specified; otherwise, the variable will be assigned an empty value.
The condition for the if parameter must be valid; otherwise, the directive may not operate as intended.