nginx-c-modules
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesenginx.org C Module Development Best Practices
nginx.org C模块开发最佳实践
Comprehensive development guide for nginx C modules, derived from the official nginx development documentation and community expertise. Contains 49 rules across 8 categories, prioritized by impact to guide correct module implementation and prevent common crashes, memory leaks, and undefined behavior.
本指南是基于官方nginx开发文档和社区经验总结的nginx C模块综合开发规范,包含8个分类下的49条规则,按影响优先级排序,用于指导模块的正确实现,避免常见崩溃、内存泄漏和未定义行为。
When to Apply
适用场景
Reference these guidelines when:
- Writing new nginx C modules (handlers, filters, upstream, load-balancers)
- Implementing configuration directives and merge logic
- Managing memory with nginx pools and shared memory zones
- Handling the HTTP request lifecycle (body reading, subrequests, finalization)
- Working with nginx's event loop, timers, and thread pools
在以下场景中参考本指南:
- 编写新的nginx C模块(处理器、过滤器、上游服务、负载均衡器)
- 实现配置指令及合并逻辑
- 使用nginx内存池和共享内存区管理内存
- 处理HTTP请求生命周期(请求体读取、子请求、请求终结)
- 操作nginx事件循环、定时器和线程池
Rule Categories by Priority
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Memory Management | CRITICAL | |
| 2 | Request Lifecycle | CRITICAL | |
| 3 | Configuration System | HIGH | |
| 4 | Handler Development | HIGH | |
| 5 | Filter Chain | MEDIUM-HIGH | |
| 6 | Upstream & Proxy | MEDIUM | |
| 7 | Event Loop & Concurrency | MEDIUM | |
| 8 | Data Structures & Strings | LOW-MEDIUM | |
| Priority | 分类 | 影响级别 | 前缀 |
|---|---|---|---|
| 1 | 内存管理 | CRITICAL | |
| 2 | 请求生命周期 | CRITICAL | |
| 3 | 配置系统 | HIGH | |
| 4 | Handler开发 | HIGH | |
| 5 | 过滤器链 | MEDIUM-HIGH | |
| 6 | 上游与代理 | MEDIUM | |
| 7 | 事件循环与并发 | MEDIUM | |
| 8 | 数据结构与字符串 | LOW-MEDIUM | |
Quick Reference
快速参考
1. Memory Management (CRITICAL)
1. 内存管理(CRITICAL)
- - Use Pool Allocation Instead of Heap malloc
mem-pool-allocation - - Check Every Allocation Return for NULL
mem-check-allocation - - Use ngx_pcalloc for Struct Initialization
mem-pcalloc-structs - - Register Pool Cleanup Handlers for External Resources
mem-cleanup-handlers - - Use ngx_pnalloc for String Data Allocation
mem-pnalloc-strings - - Avoid Relying on ngx_pfree for Pool Allocations
mem-pfree-limitations - - Use Slab Allocator for Shared Memory Zones
mem-shared-slab
- - 使用内存池分配而非堆内存malloc
mem-pool-allocation - - 检查所有内存分配的返回值是否为NULL
mem-check-allocation - - 使用ngx_pcalloc初始化结构体
mem-pcalloc-structs - - 为外部资源注册内存池清理处理器
mem-cleanup-handlers - - 使用ngx_pnalloc分配字符串数据
mem-pnalloc-strings - - 避免依赖ngx_pfree释放内存池分配的资源
mem-pfree-limitations - - 为共享内存区使用Slab分配器
mem-shared-slab
2. Request Lifecycle (CRITICAL)
2. 请求生命周期(CRITICAL)
- - Finalize Requests Exactly Once
req-finalize-once - - Never Access Request After Finalization
req-no-access-after-finalize - - Handle Request Body Reading Asynchronously
req-body-async - - Discard Request Body When Not Reading It
req-discard-body - - Use Post-Subrequest Handlers for Completion
req-subrequest-completion - - Increment Request Count Before Async Operations
req-count-reference - - Return After Internal Redirect
req-internal-redirect
- - 确保请求仅被终结一次
req-finalize-once - - 请求终结后绝不再访问
req-no-access-after-finalize - - 异步处理请求体读取
req-body-async - - 不读取请求体时主动丢弃
req-discard-body - - 使用子请求后置处理器处理完成逻辑
req-subrequest-completion - - 异步操作前增加请求引用计数
req-count-reference - - 内部重定向后直接返回
req-internal-redirect
3. Configuration System (HIGH)
3. 配置系统(HIGH)
- - Initialize Config Fields with UNSET Constants
conf-unset-init - - Merge All Config Fields in merge_loc_conf
conf-merge-all-fields - - Use Correct Context Flags for Directives
conf-context-flags - - Terminate Commands Array with ngx_null_command
conf-null-command - - Use Custom Handlers for Complex Directive Parsing
conf-custom-handler - - Set Unused Module Context Callbacks to NULL
conf-module-ctx-null - - Write Correct config Build Script for Module Compilation
conf-build-config
- - 使用UNSET常量初始化配置字段
conf-unset-init - - 在merge_loc_conf中合并所有配置字段
conf-merge-all-fields - - 为指令使用正确的上下文标志
conf-context-flags - - 使用ngx_null_command终止指令数组
conf-null-command - - 为复杂指令解析使用自定义处理器
conf-custom-handler - - 将未使用的模块上下文回调设为NULL
conf-module-ctx-null - - 编写正确的config构建脚本用于模块编译
conf-build-config
4. Handler Development (HIGH)
4. Handler开发(HIGH)
- - Send Header Before Body Output
handler-send-header-first - - Set last_buf Flag on Final Buffer
handler-last-buf - - Register Phase Handlers in postconfiguration
handler-phase-registration - - Use content_handler for Location-Specific Response Generation
handler-content-handler - - Return HTTP Status Codes for Error Responses
handler-error-page - - Use header_only for Empty Body Responses
handler-empty-response - - Use Module Context for Per-Request State
handler-module-ctx - - Register Custom Variables in preconfiguration
handler-add-variable
- - 先发送响应头再输出响应体
handler-send-header-first - - 在最后一个缓冲区设置last_buf标志
handler-last-buf - - 在postconfiguration中注册阶段处理器
handler-phase-registration - - 使用content_handler生成特定Location的响应
handler-content-handler - - 错误响应返回对应的HTTP状态码
handler-error-page - - 使用header_only返回空响应体
handler-empty-response - - 使用模块上下文存储请求级状态
handler-module-ctx - - 在preconfiguration中注册自定义变量
handler-add-variable
5. Filter Chain (MEDIUM-HIGH)
5. 过滤器链(MEDIUM-HIGH)
- - Save and Replace Top Filter in postconfiguration
filter-registration-order - - Always Call Next Filter in the Chain
filter-call-next - - Distinguish Main Request from Subrequest in Filters
filter-check-subrequest - - Iterate Buffer Chains Using cl->next Pattern
filter-buffer-chain-iteration - - Set Buffering Flag When Accumulating Response Data
filter-buffering-flag
- - 在postconfiguration中保存并替换顶层过滤器
filter-registration-order - - 始终调用过滤器链中的下一个过滤器
filter-call-next - - 在过滤器中区分主请求与子请求
filter-check-subrequest - - 使用cl->next模式遍历缓冲区链
filter-buffer-chain-iteration - - 累积响应数据时设置缓冲标志
filter-buffering-flag
6. Upstream & Proxy (MEDIUM)
6. 上游与代理(MEDIUM)
- - Build Complete Request Buffer in create_request
upstream-create-request - - Parse Upstream Response Incrementally in process_header
upstream-process-header - - Track Failures in Peer free Callback
upstream-peer-free - - Clean Up Resources in finalize_request Callback
upstream-finalize - - Enable Keepalive for Upstream Connections
upstream-connection-reuse
- - 在create_request中构建完整的请求缓冲区
upstream-create-request - - 在process_header中增量解析上游响应头
upstream-process-header - - 在Peer的free回调中追踪失败情况
upstream-peer-free - - 在finalize_request回调中清理资源
upstream-finalize - - 为上游连接启用Keepalive
upstream-connection-reuse
7. Event Loop & Concurrency (MEDIUM)
7. 事件循环与并发(MEDIUM)
- - Never Use Blocking Calls in Event Handlers
event-no-blocking - - Delete Timers Before Freeing Associated Data
event-timer-management - - Call ngx_handle_read/write_event After I/O Operations
event-handle-read-write - - Offload Blocking Operations to Thread Pool
event-thread-pool - - Use Posted Events for Deferred Processing
event-posted-events
- - 绝不在事件处理器中使用阻塞调用
event-no-blocking - - 释放关联数据前删除定时器
event-timer-management - - I/O操作后调用ngx_handle_read/write_event
event-handle-read-write - - 将阻塞操作卸载到线程池
event-thread-pool - - 使用Posted Events处理延迟任务
event-posted-events
8. Data Structures & Strings (LOW-MEDIUM)
8. 数据结构与字符串(LOW-MEDIUM)
- - Never Assume ngx_str_t Is Null-Terminated
ds-ngx-str-not-null-terminated - - Use ngx_string Macro Only with String Literals
ds-ngx-str-set-literals - - Use ngx_cpymem for Sequential Buffer Writes
ds-cpymem-pattern - - Iterate ngx_list_t Using Part-Based Pattern
ds-list-iteration - - Build Hash Tables During Configuration Only
ds-hash-readonly
- - 绝不假设ngx_str_t是NULL结尾的
ds-ngx-str-not-null-terminated - - 仅对字符串字面量使用ngx_string宏
ds-ngx-str-set-literals - - 使用ngx_cpymem进行顺序缓冲区写入
ds-cpymem-pattern - - 使用基于Part的模式遍历ngx_list_t
ds-list-iteration - - 仅在配置阶段构建哈希表
ds-hash-readonly
How to Use
使用方法
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
阅读单个参考文件获取详细说明和代码示例:
- 章节定义 - 分类结构及影响级别说明
- 规则模板 - 添加新规则的模板
Reference Files
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 分类定义及排序规则 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本及参考信息 |