当前位置: 首页 > 编程文章 >

Nginx模块编写流程及核心数据结构解析

Nginx模块编写流程及核心数据结构解析

作者:陆安时间:2025-08-30 17:12:46浏览:567

Nginx模块需在编译时静态加载,其请求处理涉及配置选择、后端代理及多级过滤机制。本文以helloworld模块为例,详解从创建目录、编写config和C文件到编译安装的完整步骤,并深入剖析ngx_command_t、ngx_http_module_t及ngx_module_t等核心结构体在模块注册与指令定义中的作用。

本文目录展开

Nginx模块处理流程概述

1. Nginx模块概述 Nginx与Apache的一个显著区别在于模块管理机制:Nginx不支持动态加载模块,所有模块必须在编译阶段通过指定路径与源码一同编译集成。 Nginx处理HTTP请求的标准流程如下: a. 客户端向Nginx服务器发起HTTP请求; b. Nginx依据配置文件中的位置匹配规则,选定合适的处理模块; c. 若为反向代理场景,负载均衡模块负责挑选一台后端服务器; d. 选定的处理模块执行具体逻辑,并将输出缓冲传递给首个过滤模块; e. 数据依次经过第一个、第二个直至第N个过滤模块的处理; h. 最终处理结果返回给客户端。

Nginx自定义模块编写步骤

2. Nginx模块编写步骤 a. 创建模块文件夹


mkdir -p /opt/nginx_hello_world 
cd /op/nginx_hello_word 

b. 创建模块配置文件


vi /opt/nginx_hello_word/config 

c. 创建模块主文件


vi /opt/nginx_hello_world/ngx_http_hello_world_module.c 

写入如下内容:


#include  
#include  
#include  
 
 
static char *ngx_http_hello_world(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); 

编写的helloworld模块


/* Commands */ 
static ngx_command_t ngx_http_hello_world_commands[] = { 
 { ngx_string("hello_world"), 
  NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS, 
  ngx_http_hello_world, 
  0, 
  0, 
  NULL }, 
 ngx_null_command 
}; 
 
static u_char ngx_hello_world[] = "hello world"; 
 
static ngx_http_module_t ngx_http_hello_world_module_ctx = { 
 NULL,         /* preconfiguration */ 
 NULL,          /* postconfiguration */ 
 NULL,         /* create main configuration */ 
 NULL,         /* init main configuration */ 
 NULL,         /* create server configuration */ 
 NULL,         /* merge server configuration */ 
 NULL,         /* create location configuration */ 
 NULL         /* merge location configuration */ 
}; 
/* hook */ 
ngx_module_t ngx_http_hello_world_module = { 
 NGX_MODULE_V1, 
 &ngx_http_hello_world_module_ctx,    /* module context */ 
 ngx_http_hello_world_commands,     /* module directives */ 
 NGX_HTTP_MODULE,      /* module type */ 
 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 
}; 
static ngx_int_t 
ngx_http_hello_world_handler(ngx_http_request_t *r) 
{ 
 ngx_int_t  rc; 
 ngx_buf_t *b; 
 ngx_chain_t out; 
 /* Http Output Buffer */ 
 r->headers_out.content_type.len = sizeof("text/plain") - 1; 
 r->headers_out.content_type.data = (u_char *) "text/plain"; 
  
 b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); 
  
 out.buf = b; 
 out.next = NULL; 
  
 b->pos = ngx_hello_world; 
 b->last = ngx_hello_world + sizeof(ngx_hello_world); 
 b->memory = 1; 
 b->last_buf = 1; 
  
 r->headers_out.status = NGX_HTTP_OK; 
 r->headers_out.content_length_n = sizeof(ngx_hello_world); 
 ngx_http_send_header(r); 
  
 return ngx_http_output_filter(r, &out); 
} 
static char * 
ngx_http_hello_world(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) 
{ 
 ngx_http_core_loc_conf_t *clcf ; 
 /* register hanlder */ 
 clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); 
 clcf->handler = ngx_http_hello_world_handler; 
 return NGX_CONF_OK; 
} 

d. 下载Nginx源码包,此处以nginx-1.0.13.tar.gz为例。 注意:在编译helloworld模块前,需先确认Nginx能否独立编译成功,以及所需的所有依赖模块是否已安装。 将helloworld模块与Nginx一起编译的命令如下:


./configure --prefix=/usr/local/nginx --add-module=/opt/nginx_hello_world/ 
make 
make install 

e. 配置nginx.conf


location= /hello { 
 hello_world; 
} 

f. 启动Nginx,访问http://localhost/hello ,即可看到helloworld模块输出的文字。 3. Hello World模块代码分析 a. ngx_command_t函数用于定义包含模块指令的静态数组ngx_http_hello_world_commands


static ngx_command_t ngx_http_hello_world_commands[] = { 
 { ngx_string("hello_world"), //设置指令名称字符串,注意不能包含空格,数据类型ngx_str_t之后会详细讲解。 
  NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS, //配置指令的合法位置,这里表示:location部分合法,并且指令没有参数。 
  ngx_http_hello_world,//回调函数,三个参数(ngx_conf_t *cf,ngx_command_t *cmd, void *conf) 
  0,//后面的参数有待发掘,我还没有用到 
  0, 
  NULL }, 
 ngx_null_command 
}; 

Hello World模块核心结构解析

b. static u_char ngx_hello_world[] ="hello world" 则是输出到屏幕的字符串。 c. ngx_http_module_t用来定义结构体ngx_http_hello_world_module_ctx:


static ngx_http_module_t ngx_http_hello_world_module_ctx = { 
 NULL,         /* 读入配置前调用*/ 
 NULL,          /* 读入配置后调用*/ 
 NULL,         /* 创建全局部分配置时调用 */ 
 NULL,         /* 初始化全局部分的配置时调用*/ 
 NULL,         /* 创建虚拟主机部分的配置时调用*/ 
 NULL,         /* 与全局部分配置合并时调用 */ 
 NULL,         /* 创建位置部分的配置时调用 */ 
 NULL         /* 与主机部分配置合并时调用*/ 
}; 

d. ngx_module_t定义结构体ngx_http_hello_world_module


ngx_module_t ngx_http_hello_world_module = { 
 NGX_MODULE_V1, 
 &ngx_http_hello_world_module_ctx,    /* module context */ 
 ngx_http_hello_world_commands,     /* module directives */ 
 NGX_HTTP_MODULE,      /* module type */ 
 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 
}; 

e. 处理函数,ngx_http_hello_world_handler,也是hello world 模块的核心部分。


static ngx_int_t 
ngx_http_hello_world_handler(ngx_http_request_t *r)//ngx_http_request_t *r 
//可以访问到客户端的头部和不久要发送的回复头部 
{ 
 ngx_int_t  rc; 
 ngx_buf_t *b; 
 ngx_chain_t out; 
 /* Http Output Buffer */ 
 r->headers_out.content_type.len = sizeof("text/plain") - 1; 
 r->headers_out.content_type.data = (u_char *) "text/plain"; 
  
 b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); 
  
 out.buf = b; 
 out.next = NULL; 
  
 b->pos = ngx_hello_world; 
 b->last = ngx_hello_world + sizeof(ngx_hello_world); 
 b->memory = 1; 
 b->last_buf = 1; 
  
 r->headers_out.status = NGX_HTTP_OK; 
 r->headers_out.content_length_n = sizeof(ngx_hello_world); 
 ngx_http_send_header(r); 
  
 return ngx_http_output_filter(r, &out); 
} 

helloworld模块里面涉及最重要的数据就是ngx_module_t指针数组,这个指针数组包含了当前编译版本支持的所有模块,这个指针数组定义实在自动脚本生成的objs/ngx_modules.c中,如下:


 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_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_upstream_module; 
 extern ngx_module_t ngx_http_static_module; 
 extern ngx_module_t ngx_http_autoindex_module; 
 extern ngx_module_t ngx_http_index_module; 
 extern ngx_module_t ngx_http_auth_basic_module; 
 extern ngx_module_t ngx_http_access_module; 
 extern ngx_module_t ngx_http_limit_zone_module; 
 extern ngx_module_t ngx_http_limit_req_module; 
 extern ngx_module_t ngx_http_geo_module; 
 extern ngx_module_t ngx_http_map_module; 
 extern ngx_module_t ngx_http_split_clients_module; 
 extern ngx_module_t ngx_http_referer_module; 
 extern ngx_module_t ngx_http_rewrite_module; 
 extern ngx_module_t ngx_http_proxy_module; 
 extern ngx_module_t ngx_http_fastcgi_module; 
 extern ngx_module_t ngx_http_uwsgi_module; 
 extern ngx_module_t ngx_http_scgi_module; 
 extern ngx_module_t ngx_http_memcached_module; 
 extern ngx_module_t ngx_http_empty_gif_module; 
 extern ngx_module_t ngx_http_browser_module; 
 extern ngx_module_t ngx_http_upstream_ip_hash_module; 
 extern ngx_module_t ngx_http_cache_purge_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_postpone_filter_module; 
 extern ngx_module_t ngx_http_ssi_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_core_module, 
  &ngx_errlog_module, 
  &ngx_conf_module, 
  &ngx_events_module, 
  &ngx_event_core_module, 
  &ngx_epoll_module, 
  &ngx_http_module, 
  &ngx_http_core_module, 
  &ngx_http_log_module, 
  &ngx_http_upstream_module, 
  &ngx_http_static_module, 
  &ngx_http_autoindex_module, 
  &ngx_http_index_module, 
  &ngx_http_auth_basic_module, 
  &ngx_http_access_module, 
  &ngx_http_limit_zone_module, 
  &ngx_http_limit_req_module, 
  &ngx_http_geo_module, 
  &ngx_http_map_module, 
  &ngx_http_split_clients_module, 
  &ngx_http_referer_module, 
  &ngx_http_rewrite_module, 
  &ngx_http_proxy_module, 
  &ngx_http_fastcgi_module, 
  &ngx_http_uwsgi_module, 
  &ngx_http_scgi_module, 
  &ngx_http_memcached_module, 
  &ngx_http_empty_gif_module, 
  &ngx_http_browser_module, 
  &ngx_http_upstream_ip_hash_module, 
  &ngx_http_cache_purge_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_postpone_filter_module, 
  &ngx_http_ssi_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 
 }; 

这里只有每个模块变量的声明,并且每个模块的定义都包含在自己的模块文件当中,比如ngx_core_module定义在src/core/nginx.c中:


ngx_module_t ngx_core_module = { 
 NGX_MODULE_V1, 
 &ngx_core_module_ctx,     /* module context */ 
 ngx_core_commands,      /* module directives */ 
 NGX_CORE_MODULE,      /* module type */ 
 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 
}; 

是不是跟helloworld里面非常相似了,没错,他们都是模块,唯一的不同点就是helloworld是你另外加进去的。 到现在位置也只是初探nginx的模块,最后提一张别人画的nginx的模块图,有助于接下来的学习。

上一篇
PHP安装全攻略:APACHE

本文介绍在中文Windows 98环境下,将Apache 1.3.11与PHP 3.0.15进行集成的具体步骤。主要涵盖解压PHP文件、修改php3.ini以指定文档根目录及扩展路径、启用MySQL等动态链接库,以及在Apache的httpd.conf中配置ScriptAlias、AddType和Action指令,最终通过浏览器测试验证环境是否成功部署。

下一篇
Nginx反向代理location和proxy_pass配置规则详细总结

本文详解Nginx中location的模糊匹配机制及proxy_pass的路径拼接规则。重点说明location是否以斜杠结尾对请求匹配的影响,以及proxy_pass后是否带斜杠如何决定原始路径是否被保留。通过具体示例展示绝对路径与普通路径在代理转发时的差异,帮助开发者避免常见的路径错误问题。

相关文章

更多
PHP操作Redis String、Hash和List数据结构代码实例

使用 Predis 或 phpredis 扩展,通过连接实例直接调用 set 、 hSet 、 rPush 等方法操作对应数据结构。

2026.06.12 976
PHP基础排序算法详解:冒泡、插入与快速排序实现

本文详细解析了PHP中三种核心排序算法的实现原理与代码。通过具体示例展示了冒泡排序、插入排序及快速排序的逻辑,涵盖基本排序技巧,帮助开发者掌握高效的数据排列方法,提升PHP编程实战能力。

2025.06.05 950
查询JSON数据结构的8种方式简介

本文介绍了八种用于查询JSON数据结构的工具和方法,包括基于SQL的JsonSQL、类似XPath的JSONPath、类jQuery的jFunk、提供数据库功能的TaffyDB、支持LINQ语法的linq.js、实现实时查询的objeq、使用CSS选择符的json:select()以及Paul提出的数组过滤方法。这些工具各有特点,适用于不同的开发场景和需求。

2026.09.28 925
JavaScript链表数据结构详解与实现

链表是一种存储有序元素集合的数据结构,其节点在内存中非连续分布,通过指针链接。相比数组,链表支持动态扩容且插入移除操作无需移动其他元素,但访问元素需从头迭代。本文结合《javascript数据结构和算法》内容,解析链表核心机制并提供基础实现代码。

2025.05.31 832
PHP 无限级分类的数据结构与遍历

无限级分类通常用父子关系串起各级记录。准备数据时先确认根节点与父节点标识,再把同一父节点的子项集中起来,生成树时检查缺失父项和循环引用,确保异常数据不会让遍历无法结束。

2025.02.24 826
JavaScript 数据结构之链表的实现

在 JavaScript 中,数组并非所有场景下的最佳选择,特别是在频繁增删元素时,链表能避免移动其他元素的开销。本文详细讲解了基于对象的单向链表实现,包括 Node 和 LinkedList 类的定义及 find、insert、remove 等方法。随后扩展至双向链表,通过增加 front 属性支持反向遍历,并介绍了循环链表通过将尾节点指向头节点形成闭环的处理方式及防死循环技巧。

2026.06.28 823

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。