nginx-c-modules

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

nginx.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

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Memory ManagementCRITICAL
mem-
2Request LifecycleCRITICAL
req-
3Configuration SystemHIGH
conf-
4Handler DevelopmentHIGH
handler-
5Filter ChainMEDIUM-HIGH
filter-
6Upstream & ProxyMEDIUM
upstream-
7Event Loop & ConcurrencyMEDIUM
event-
8Data Structures & StringsLOW-MEDIUM
ds-
Priority分类影响级别前缀
1内存管理CRITICAL
mem-
2请求生命周期CRITICAL
req-
3配置系统HIGH
conf-
4Handler开发HIGH
handler-
5过滤器链MEDIUM-HIGH
filter-
6上游与代理MEDIUM
upstream-
7事件循环与并发MEDIUM
event-
8数据结构与字符串LOW-MEDIUM
ds-

Quick Reference

快速参考

1. Memory Management (CRITICAL)

1. 内存管理(CRITICAL)

  • mem-pool-allocation
    - Use Pool Allocation Instead of Heap malloc
  • mem-check-allocation
    - Check Every Allocation Return for NULL
  • mem-pcalloc-structs
    - Use ngx_pcalloc for Struct Initialization
  • mem-cleanup-handlers
    - Register Pool Cleanup Handlers for External Resources
  • mem-pnalloc-strings
    - Use ngx_pnalloc for String Data Allocation
  • mem-pfree-limitations
    - Avoid Relying on ngx_pfree for Pool Allocations
  • mem-shared-slab
    - Use Slab Allocator for Shared Memory Zones
  • mem-pool-allocation
    - 使用内存池分配而非堆内存malloc
  • mem-check-allocation
    - 检查所有内存分配的返回值是否为NULL
  • mem-pcalloc-structs
    - 使用ngx_pcalloc初始化结构体
  • mem-cleanup-handlers
    - 为外部资源注册内存池清理处理器
  • mem-pnalloc-strings
    - 使用ngx_pnalloc分配字符串数据
  • mem-pfree-limitations
    - 避免依赖ngx_pfree释放内存池分配的资源
  • mem-shared-slab
    - 为共享内存区使用Slab分配器

2. Request Lifecycle (CRITICAL)

2. 请求生命周期(CRITICAL)

  • req-finalize-once
    - Finalize Requests Exactly Once
  • req-no-access-after-finalize
    - Never Access Request After Finalization
  • req-body-async
    - Handle Request Body Reading Asynchronously
  • req-discard-body
    - Discard Request Body When Not Reading It
  • req-subrequest-completion
    - Use Post-Subrequest Handlers for Completion
  • req-count-reference
    - Increment Request Count Before Async Operations
  • req-internal-redirect
    - Return After 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)

  • conf-unset-init
    - Initialize Config Fields with UNSET Constants
  • conf-merge-all-fields
    - Merge All Config Fields in merge_loc_conf
  • conf-context-flags
    - Use Correct Context Flags for Directives
  • conf-null-command
    - Terminate Commands Array with ngx_null_command
  • conf-custom-handler
    - Use Custom Handlers for Complex Directive Parsing
  • conf-module-ctx-null
    - Set Unused Module Context Callbacks to NULL
  • conf-build-config
    - Write Correct config Build Script for Module Compilation
  • conf-unset-init
    - 使用UNSET常量初始化配置字段
  • conf-merge-all-fields
    - 在merge_loc_conf中合并所有配置字段
  • conf-context-flags
    - 为指令使用正确的上下文标志
  • conf-null-command
    - 使用ngx_null_command终止指令数组
  • conf-custom-handler
    - 为复杂指令解析使用自定义处理器
  • conf-module-ctx-null
    - 将未使用的模块上下文回调设为NULL
  • conf-build-config
    - 编写正确的config构建脚本用于模块编译

4. Handler Development (HIGH)

4. Handler开发(HIGH)

  • handler-send-header-first
    - Send Header Before Body Output
  • handler-last-buf
    - Set last_buf Flag on Final Buffer
  • handler-phase-registration
    - Register Phase Handlers in postconfiguration
  • handler-content-handler
    - Use content_handler for Location-Specific Response Generation
  • handler-error-page
    - Return HTTP Status Codes for Error Responses
  • handler-empty-response
    - Use header_only for Empty Body Responses
  • handler-module-ctx
    - Use Module Context for Per-Request State
  • handler-add-variable
    - Register Custom Variables in preconfiguration
  • handler-send-header-first
    - 先发送响应头再输出响应体
  • handler-last-buf
    - 在最后一个缓冲区设置last_buf标志
  • handler-phase-registration
    - 在postconfiguration中注册阶段处理器
  • handler-content-handler
    - 使用content_handler生成特定Location的响应
  • handler-error-page
    - 错误响应返回对应的HTTP状态码
  • handler-empty-response
    - 使用header_only返回空响应体
  • handler-module-ctx
    - 使用模块上下文存储请求级状态
  • handler-add-variable
    - 在preconfiguration中注册自定义变量

5. Filter Chain (MEDIUM-HIGH)

5. 过滤器链(MEDIUM-HIGH)

  • filter-registration-order
    - Save and Replace Top Filter in postconfiguration
  • filter-call-next
    - Always Call Next Filter in the Chain
  • filter-check-subrequest
    - Distinguish Main Request from Subrequest in Filters
  • filter-buffer-chain-iteration
    - Iterate Buffer Chains Using cl->next Pattern
  • filter-buffering-flag
    - Set Buffering Flag When Accumulating Response Data
  • filter-registration-order
    - 在postconfiguration中保存并替换顶层过滤器
  • filter-call-next
    - 始终调用过滤器链中的下一个过滤器
  • filter-check-subrequest
    - 在过滤器中区分主请求与子请求
  • filter-buffer-chain-iteration
    - 使用cl->next模式遍历缓冲区链
  • filter-buffering-flag
    - 累积响应数据时设置缓冲标志

6. Upstream & Proxy (MEDIUM)

6. 上游与代理(MEDIUM)

  • upstream-create-request
    - Build Complete Request Buffer in create_request
  • upstream-process-header
    - Parse Upstream Response Incrementally in process_header
  • upstream-peer-free
    - Track Failures in Peer free Callback
  • upstream-finalize
    - Clean Up Resources in finalize_request Callback
  • upstream-connection-reuse
    - Enable Keepalive for Upstream Connections
  • upstream-create-request
    - 在create_request中构建完整的请求缓冲区
  • upstream-process-header
    - 在process_header中增量解析上游响应头
  • upstream-peer-free
    - 在Peer的free回调中追踪失败情况
  • upstream-finalize
    - 在finalize_request回调中清理资源
  • upstream-connection-reuse
    - 为上游连接启用Keepalive

7. Event Loop & Concurrency (MEDIUM)

7. 事件循环与并发(MEDIUM)

  • event-no-blocking
    - Never Use Blocking Calls in Event Handlers
  • event-timer-management
    - Delete Timers Before Freeing Associated Data
  • event-handle-read-write
    - Call ngx_handle_read/write_event After I/O Operations
  • event-thread-pool
    - Offload Blocking Operations to Thread Pool
  • event-posted-events
    - Use Posted Events for Deferred Processing
  • event-no-blocking
    - 绝不在事件处理器中使用阻塞调用
  • event-timer-management
    - 释放关联数据前删除定时器
  • event-handle-read-write
    - I/O操作后调用ngx_handle_read/write_event
  • event-thread-pool
    - 将阻塞操作卸载到线程池
  • event-posted-events
    - 使用Posted Events处理延迟任务

8. Data Structures & Strings (LOW-MEDIUM)

8. 数据结构与字符串(LOW-MEDIUM)

  • ds-ngx-str-not-null-terminated
    - Never Assume ngx_str_t Is Null-Terminated
  • ds-ngx-str-set-literals
    - Use ngx_string Macro Only with String Literals
  • ds-cpymem-pattern
    - Use ngx_cpymem for Sequential Buffer Writes
  • ds-list-iteration
    - Iterate ngx_list_t Using Part-Based Pattern
  • ds-hash-readonly
    - Build Hash Tables During Configuration Only
  • ds-ngx-str-not-null-terminated
    - 绝不假设ngx_str_t是NULL结尾的
  • ds-ngx-str-set-literals
    - 仅对字符串字面量使用ngx_string宏
  • ds-cpymem-pattern
    - 使用ngx_cpymem进行顺序缓冲区写入
  • ds-list-iteration
    - 使用基于Part的模式遍历ngx_list_t
  • 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

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md分类定义及排序规则
assets/templates/_template.md新规则模板
metadata.json版本及参考信息