实战开发一个 Nginx 扩展 (Nginx Module)

实战开发一个 Nginx 扩展 (Nginx Module)#

如果这个 repo 对你有帮助 欢迎 star fork#

repo 地址 https://github.com/wujunze/nginx-http-echo-module #

nginx_module_echo#

使用 echo 指令输出一个字符串

Nginx 版本#

Nginx1.0.10 https://github.com/nginx/nginx/releases/ta...
image

开发环境#

OS : CentOS Linux release 7.2.1511 (Core)

image
image

安装一个干净的 Nginx#

  1. 下载 Nginx10.10 并且解压它
    image

  2. 安装 gcc 和 Nginx 需要的 lib
    image
    image

  3. ./configure --prefix=/usr/local/nginx && make && make install
    image
    image
    image

  4. 运行 Nginx
    image
    image

定义模块配置结构#

typedef struct {
    ngx_str_t ed;  //该结构体定义在这里 https://github.com/nginx/nginx/blob/master/src/core/ngx_string.h
} ngx_http_echo_loc_conf_t;

image

定义 echo 模块的指令和参数转化函数#

image

定义模块 Context#

  1. 定义 ngx_http_module_t 类型的结构体变量
    image
  2. 初始化一个配置结构体
    image
  3. 将其父 block 的配置信息合并到此结构体 实现了配置的继承
    image

编写 Handler 模块真正干活儿的部分#

image

组合 Nginx Module#

image

整理模块代码 按照 Nginx 官方规范#

image

编写 config 文件#

ngx_addon_name=ngx_http_echo_module
HTTP_MODULES="$HTTP_MODULES ngx_http_echo_module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/src/ngx_http_echo_module.c"

编译安装 echo 模块#

 ./configure --prefix=/usr/local/nginx/ --add-module=/root/ngx_dev && make && make install

安装成功#

image

修改 Nginx 配置文件测试 Module#

image

Nginx echo Module 运行成功#

image

Thanks#

参考文档#

  1. http://wiki.nginx.org/Configuration
  2. http://tengine.taobao.org/book/
  3. http://blog.codinglabs.org/articles/intro-...
  4. https://www.nginx.com/resources/wiki/modul...
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 6年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 12

一楼:grin:

8年前 评论

看不懂,但是觉得很厉害 :thumbsup:

8年前 评论

有啥应用场景吗?还是作为一个教程?

8年前 评论

@Hanccc :smile:
@JokerLinly :laughing:
@overtrue 谢谢鼓励 :laughing:
@dinghua 主要是通过开发一个简单的 Nginx Module 来学习 Nginx 模块机制和 Nginx 模块开发

8年前 评论
imxfly

@wujunze Nginx 模块开发太累了,不如用 OpenResty,使用 Lua 语言轻松开发:open_mouth:

8年前 评论

@Stephen 对的:smile: 生产环境建议用 OpenResty , 模块丰富:thumbsup: Lua 写模块不用重新编译 Nginx, 本教程主要目的是通过开发一个简单的 Nginx Module 来学习 Nginx 模块机制和 Nginx 模块开发

8年前 评论

对啊,有应用场景嘛 做一个扩展能干嘛?

8年前 评论

@736713830 能学习 Nginx 内核 能学习网络 IO 模型 能学习 Nginx 模块机制 哈哈

8年前 评论

@wujunze 涨姿势了........

8年前 评论