内建变量
免费的午餐,不用任何手工劳动就能使用的变量——nginx帮你创建了。上面log_format中使用的变量全部是内建变量。有几个特殊的内建变量族,现在列举一下:
cookie_XXX | 对应cookie中的XXX参数 |
arg_XXX | 对应uri中的XXX参数 |
http_XXX | 对应http请求头中的XXX字段 |
sent_http_XXX | 对应http响应头中的XXX字段 |
upstream_http_XXX | 对应nginx传递给后端服务器的请求头中的XXX字段 |
创建变量
创建变量使用ngx_http_add_variable函数。
ngx_http_variable_t * ngx_http_add_variable(ngx_conf_t *cf, ngx_str_t *name, ngx_uint_t flags); |
其中name是变量的名称
flags是变量的标志:
l NGX_HTTP_VAR_CHANGEABLE:允许重复定义;
l NGX_HTTP_VAR_NOCACHEABLE:变量值不可以被缓存,每次使用必须计算;
l NGX_HTTP_VAR_INDEXED:指示变量值存储在数组中,当使用ngx_http_get_variable函数获取变量时不会每次都为变量分配值空间;
l NGX_HTTP_VAR_NOHASH:配置解析完以后,变量名不进hash索引,处理请求时不可以用变量名访问变量。
Use nginx variable:
code1 and code2 is a example for use nginx variable.
Add code to judge your configure value's type.
code 1:
static char *
ngx_http_map_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_compile_complex_value_t ccv;
ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));
ccv.cf = cf;
ccv.value = &value[1];
ccv.complex_value = &map->value;
if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (cv.lengths == NULL) { # whether this is a variable or constant
ngx_conf_set_size_slot(cf, cmd, conf);
}
}
code 2:
ngx_http_map_ctx_t *map = (ngx_http_map_ctx_t *) data;
ngx_str_t val;
if (ngx_http_complex_value(r, &map->value, &val) != NGX_OK) {
return NGX_ERROR;
}