模块编译与集成
Nginx 模块通过 config 文件描述编译规则,集成到 Nginx 构建系统,支持静态编译和动态模块两种方式。
静态模块编译
config 文件结构
Bash
# 模块类型
ngx_addon_name=ngx_http_my_module
# 模块分类(HTTP_FILTER/HTTP_AUX_FILTER/HTTP)
if test -n "$ngx_module_link"; then
ngx_module_type=HTTP
ngx_module_name="$ngx_addon_name"
ngx_module_srcs="$ngx_addon_dir/ngx_http_my_module.c"
ngx_module_incs="$ngx_addon_dir"
. auto/module
else
HTTP_MODULES="$HTTP_MODULES $ngx_addon_name"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_my_module.c"
NGX_ADDON_DEPS="$ngx_addon_dir/ngx_http_my_module.h"
fi
编译流程
Bash
# 1. 配置阶段
./configure --add-module=/path/to/my_module
# 2. 生成 Makefile 和 objs/ngx_modules.c
# objs/ngx_modules.c 自动注册模块
ngx_module_t *ngx_modules[] = {
...
&ngx_http_my_module,
NULL
};
# 3. 编译
make
# 4. 安装
make install
--add-module将模块静态编译进 Nginx 二进制文件,重启生效,不可卸载。
动态模块编译
config 文件(动态模块)
Bash
ngx_module_name=ngx_http_my_module
ngx_module_incs=$ngx_addon_dir
ngx_module_srcs=$ngx_addon_dir/ngx_http_my_module.c
ngx_module_deps=
ngx_module_libs=
ngx_module_link=DYNAMIC
. auto/module
编译与加载
Bash
# 编译为动态模块
./configure --with-compat --add-dynamic-module=/path/to/my_module
make modules
# 输出 objs/ngx_http_my_module.so
# 配置加载
load_module modules/ngx_http_my_module.so;
动态模块通过
load_module指令加载,无需重新编译 Nginx 核心。
模块注册结构
模块定义
C
ngx_module_t ngx_http_my_module = {
NGX_MODULE_V1,
&ngx_http_my_module_ctx, // 模块上下文
ngx_http_my_commands, // 配置指令
NGX_HTTP_MODULE, // 模块类型
NULL, // init master
NULL, // init module
NULL, // init process
NULL, // init thread
NULL, // exit thread
NULL, // exit process
NULL, // exit master
NGX_MODULE_V1_PADDING
};
模块上下文(HTTP)
C
static ngx_http_module_t ngx_http_my_module_ctx = {
NULL, // preconfiguration
ngx_http_my_init, // postconfiguration
ngx_http_my_create_main_conf, // create main configuration
NULL, // init main configuration
NULL, // create server configuration
NULL, // merge server configuration
ngx_http_my_create_loc_conf, // create location configuration
ngx_http_my_merge_loc_conf // merge location configuration
};
模块依赖与头文件
依赖声明
Bash
# config 文件声明依赖
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/src/ngx_http_my_module.c"
NGX_ADDON_DEPS="$ngx_addon_dir/include/ngx_http_my_module.h"
# 需要外部库
CORE_LIBS="$CORE_LIBS -lmylib"
CORE_INCS="$CORE_INCS $ngx_addon_dir/include"
编译选项
| 选项 | 说明 |
|---|---|
--add-module=PATH | 静态编译模块 |
--add-dynamic-module=PATH | 动态编译模块 |
--with-compat | 启用动态模块兼容性检查 |
--with-cc-opt | 添加编译器 C 选项 |
--with-ld-opt | 添加链接器选项 |
要点总结
- 静态模块通过
--add-module编译进 Nginx 二进制,动态模块通过--add-dynamic-module生成 .so 文件 - config 文件描述模块源文件、类型和依赖,是 Nginx 构建系统识别模块的唯一方式
- 模块通过
ngx_module_t结构注册,包含上下文、指令集和生命周期回调 - 动态模块通过
load_module指令加载,支持热插拔 - 编译流程:config → configure → Makefile → make → 安装
📝 发现内容有误?点击此处直接编辑