最好的nginx模块开发例子

拿酷网上的一篇好文。

nginx源码分析03-最好的nginx模块开发例子

0.引子

在开始阅读源码之前,动手实践下将对你有很大的帮助。本文将搭一个入门级的环境,一步步演示模块开发是怎么回事。

1.源码下载

  • a. pcre-8.20下载
  • b. nginx-1.2.1源码下载
  • c. nginx hello module模块下载

2.安装

...

3. 附上源码: ngx_http_hello_module.c

 
 
/*
 * Copyright (C) FatHong
 * Copyright (C) http://www.nuckoo.com
 */
 
/*
 *
 * 模块名称:hello
 *
 * 功能:此模块用于学习,它将根据配置选项输出 hello: config-content
 *
 * 指令:hello 参数;
 *
 * 访问:http://yourdomain/hello, 输出 hello: fathong
 *
 * location /hello {
 *     hello  fathong;
 * }
 *
 */
 
 
/* 
 * 关键词: 模块
 *
 * 如何开发nginx模块?一切以模块为核心,本模块名称为 hello。
 * 由于模块有4个类型:core, event, http, mail,本模块类型为http,所以模块名称为 ngx_http_hello_module。
 */
 
/* 1. 包含头文件 */
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
 
 
/*
 * 关键词:模块配置结构体
 *
 * 由于有配置选项,我们需要配置结构体来装载它的信息,每个模块有自己的一个配置结构体。
 * ngx_http_hello_loc_conf_t,看下这命名规则 ngx_http_<your module>_<pos>_conf_t
 * pos有3种,main, srv, loc。http模块都是如此,指令可以指定放置的位置,此模块hello指令只允许放在loc里。
 */
 
/* 2. 声明模块配置结构体 */
typedef struct {
    ngx_str_t  output;
} ngx_http_hello_loc_conf_t;
 
 
/*
 * 关键词:模块配置结体构创建函数(模块上下文)、指令集、指令
 *
 * 既然有了模块配置结构体,那就需要一个专门的函数创建它,每个模块都有自己的配置结构体函数。
 * ngx_http_hello_create_loc_conf,看下命名规则:ngx_http_<your module>_create_<pos>_conf
 * 这个函数赋值在模块上下文中,后面会讲到模块上下文。
 *
 * 模块自己有自己的模块指令集,通过这些指令,可以匹配解析配置文件中属于它的配置。
 * ngx_http_hello_commands。命名规则:ngx_http_<your module>_commands
 *
 * 指令集由指令组成,每个配置选项对应一个指令,每个指令会有一个处理解析函数。比如hello => ngx_http_hello。
 */

未完..

更多请看 http://www.nuckoo.com/nginx/03.html

你可能感兴趣的:(nginx源码分析,nginx模块开发)