Nginx创建变量值

目标:在nginx模块中,创建变量,而且赋值 ,能够在配置文件中直接通过变量值获取值。

1.在readconf阶段,插入变量值:

     保存对应的index值,以后使用。
     value[1]为变量的名字。     

    ngx_http_variable_t *v;         
    ngx_int_t index;                                                                                                                              
    ngx_str_t *value;                                                                                                                             
    value = static_cast<ngx_str_t*>(cf->args->elts);                                                                                              
                                                              
    v = ngx_http_add_variable(cf, &value[1] , NGX_HTTP_VAR_CHANGEABLE);                                                                         
    if (v == NULL) {                                                                                                                           
        return (char*)NGX_CONF_ERROR;                                                                                              
    }                                                                                                                                            
                                                                                                                                              
    index = ngx_http_get_variable_index(cf, &value[1]);                                                                                       
    if (index == NGX_ERROR) {                                                                                                              
        return (char*)NGX_CONF_ERROR;                                                                                                
    }                                      
2.在需要修改的时候,使用以下的代码:
    ngx_http_core_main_conf_t  *cmcf;
    ngx_http_variable_value_t  *v;
    cmcf = (ngx_http_core_main_conf_t*)ngx_http_get_module_main_conf(r, ngx_http_core_module);
    v = ngx_http_get_indexed_variable( r , v_index ) ;

    if( r->variables == NULL )
        printf("variables null\n");

    v->len = ilen ;
    v->valid = 1;
    v->no_cacheable = 0;
    v->not_found = 0;
  
    修改 v->data 为变量的值。
posted @ 2011-02-21 09:59  梁星  阅读(4731)  评论(0编辑  收藏  举报
Mobile and Web Analytics