How to read variable in C code?

Maxim Dounin mdounin at
Sat Dec 31 02:42:34 UTC 2016


On Fri, Dec 30, 2016 at 02:36:00PM +0100, Witold Filipczyk wrote:

> Hi,
> there is map:
> map $http_host $hosts {
>   hostnames;
>   default 0;
> 1;
> 1;
>   ...
> 1;
> }
> How to read the value of $hosts in C module code?

If you only need a single variable, most effective approach is to 
use indexed variables.  The ngx_http_get_variable_index() function 
is used to obtain an index during configuration parsing / module 
initialization, and ngx_http_get_indexed_variable() to obtain a 
value at runtime.  E.g., memcached module uses this to access 
$memcached_key variable, see here:

More universal approach is to use complex values.  Complex values 
can contain arbitrary combinations of variables and static 
strings.  During configuration parsing complex values are compiled 
using ngx_http_compile_complex_value() 
(ngx_http_set_complex_value_slot can do it automatically if there 
is a dedicated configuration directive), and then 
ngx_http_complex_value() can be used to obtain a value.  E.g., map 
itself uses complex value to handle the first parameter, 
"$http_host" in your case, see here:

> How to make it right, that's mean do not evaluate it more than once per request?

Map results are automatically cached by nginx, much like all 
variables not explicitly declared as non-cacheable, so you don't 
really need to worry.  On the other hand, usually it's a good idea 
to remember the value obtained in your module data if you are 
going to use it again.

Maxim Dounin

More information about the nginx-devel mailing list