前两篇文章看了后相信可以写出五花八门的有用的Nginx插件了。我写的都是一些基本的流程,Nginx提供的函数可以很直观地从函数名上表现出来,所以也没过多的说明。这一章说说Nginx的配置,主要是配置模块命令的参数,顺便提一下HTTP的参数处理。
本文链接
这次实现一个提供命令 “pw” 的模块,这个命令需要一个参数:
static ngx_command_t ngx_http_rw_commands[] = {
{
ngx_string("rw"),
NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, //需要1个参数
ngx_http_rw_setup,
0,
0,
NULL
},
ngx_null_command
};
模块命令调用的参数在这个command的set函数被内核调用的时候可以取得,即是内核传过来的ngx_conf_t变量里可以取得,cf->args->elts是一个参数字符串数组。
这时取到的参数我们可以存起来,也可以根据参数的不同指定不同的处理函数,本文的例子是用的第二种方式。
char* ngx_http_rw_setup(ngx_conf_t *cf, ngx_command_t *cmd, void *conf){
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
ngx_str_t* args;
args=cf->args->elts;
//根据参数的不同指定不同的处理函数。
if(ngx_strcmp("1",args[1].data)==0){ //如果参数是1
clcf->handler = ngx_http_pw1_handler;
}
else if(ngx_strcmp("2",args[1].data)==0){ //如果参数是2
clcf->handler = ngx_http_pw2_handler;
}
else{//其它参数
clcf->handler = ngx_http_pw3_handler;
}
return NGX_CONF_OK;
}
Continue reading “熟悉Nginx,为Nginx编写插件(三)”