看Nginx代码时, src目录下的结构为core、event、http和os,可见Nginx的代码层次十分清晰;同样,我们在代码中也经常看到ngx_modules这个全局变量,可见在Nginx中是有模块概念的,事实上Nginx的设计就是高度模块化的,这一节我们学习下Nginx的模块结构体和ngx_modules数组。
/* core/ngx_core.h */
typedef struct ngx_module_s ngx_module_t;
/* core/ngx_conf_file.h */
struct ngx_module_s { // Nginx模块结构体定义
ngx_uint_t ctx_index; // Nginx模块有多种类型, 目前来说有NGX_CORE_MODULE、NGX_EVENT_MODULE、NGX_HTTP_MODULE这3种,
// 每个模块都从属于其中一种类型, ctx_index就是模块在所属类型下的索引
ngx_uint_t index; // 模块在ngx_modules数组中的索引
void *ctx; // 模块上下文, 每个模块都可以定义自己的上下文
ngx_command_t *commands; // 模块的指令集
ngx_uint_t type; // 模块类型
ngx_int_t (*init_module)(ngx_cycle_t *cycle); // 用于初始化模块的函数指针
ngx_int_t (*init_process)(ngx_cycle_t *cycle); // 用于执行模块特定的进程初始化工作的函数指针
#if 0
ngx_int_t (*init_thread)(ngx_cycle_t *cycle); // 用于执行模块特定的线程初始化工作的函数指针
#endif
};
/* ngx_modules.c
* 该文件是在编译Nginx, 由脚本自动生成的
*/
#include <ngx_config.h>
#include <ngx_core.h>
extern ngx_module_t ngx_core_module;
extern ngx_module_t ngx_errlog_module;
extern ngx_module_t ngx_conf_module;
extern ngx_module_t ngx_events_module;
extern ngx_module_t ngx_event_core_module;
extern ngx_module_t ngx_rtsig_module;
extern ngx_module_t ngx_epoll_module;
extern ngx_module_t ngx_http_module;
extern ngx_module_t ngx_http_core_module;
extern ngx_module_t ngx_http_log_module;
extern ngx_module_t ngx_http_static_module;
extern ngx_module_t ngx_http_index_module;
extern ngx_module_t ngx_http_access_module;
extern ngx_module_t ngx_http_rewrite_module;
extern ngx_module_t ngx_http_proxy_module;
extern ngx_module_t ngx_http_write_filter_module;
extern ngx_module_t ngx_http_header_filter_module;
extern ngx_module_t ngx_http_chunked_filter_module;
extern ngx_module_t ngx_http_range_header_filter_module;
extern ngx_module_t ngx_http_gzip_filter_module;
extern ngx_module_t ngx_http_charset_filter_module;
extern ngx_module_t ngx_http_userid_filter_module;
extern ngx_module_t ngx_http_headers_filter_module;
extern ngx_module_t ngx_http_copy_filter_module;
extern ngx_module_t ngx_http_range_body_filter_module;
extern ngx_module_t ngx_http_not_modified_filter_module;
ngx_module_t *ngx_modules[] = { // ngx_modules数组, 这里面的模块顺序很重要, 不能随便打乱
&ngx_core_module,
&ngx_errlog_module,
&ngx_conf_module,
&ngx_events_module,
&ngx_event_core_module,
&ngx_rtsig_module,
&ngx_epoll_module,
&ngx_http_module,
&ngx_http_core_module,
&ngx_http_log_module,
&ngx_http_static_module,
&ngx_http_index_module,
&ngx_http_access_module,
&ngx_http_rewrite_module,
&ngx_http_proxy_module,
&ngx_http_write_filter_module,
&ngx_http_header_filter_module,
&ngx_http_chunked_filter_module,
&ngx_http_range_header_filter_module,
&ngx_http_gzip_filter_module,
&ngx_http_charset_filter_module,
&ngx_http_userid_filter_module,
&ngx_http_headers_filter_module,
&ngx_http_copy_filter_module,
&ngx_http_range_body_filter_module,
&ngx_http_not_modified_filter_module,
NULL
};