跳转至

nginx


模块

模块生命周期

  • 主进程解析配置时,调用指令配置函数
  • 解析完后,调用init_module
  • 主进程创建工作进程,工作进程调用init_process
  • 当工作线程收到终止信号,调用exit_process
  • 主线程调用exit_master

模块种类

  • NGX_CORE_MODULE
  • NGX_EVENT_MODULE
  • NGX_HTTP_MODULE
  • NGX_MAIL_MODULE
  • NGX_STREAM_MODULE

核心模块

  • ngx_core_module,
  • ngx_errlog_module,
  • ngx_regex_module,
  • ngx_thread_pool_module
  • ngx_openssl_module

配置指令

connection

主进程listen,fork,accept,创建ngx_connection_t

tcp链接得封装 ngx_connection_t 客户端请求 upstream模块 客户端创建ngx_connection_t,链接/读写

worker_connections保存链接

反向代理 worker_connections * worker_processes/2

ngx_accept_disabled的变量来控制是否去竞争accept_mutex锁

当空余连接越少时,ngx_accept_disable越大,于是让出的机会就越多,这样其它进程获取锁的机会也就越大。

监听socket可读
调用ngx_event_accept接收新得连接
创建ngx_connection_t保存信息

初期调用ngx_http_init_connection初始化HTTP连接
创建ngx_http_connection_t,存储到ngx_connection_t数据域 代理协议解析,ssl握手开始

当客户端数据可读
调用ngx_http_wait_request_handler读取数据
注册请求行读取函数ngx_http_process_request_line
并创建ngx_http_request_t
存储到ngx_connection_t数据域

ngx_http_process_request_line读取请求行
数据存进connection的buffer里.
client_header_buffer_size指令设置该段内存大小
如果预留内存不够, large_client_header_buffers可以分配更大内存

设置ngx_http_process_request_headers读取请求头.

当请求头读取解析完成后
调用ngx_http_core_run_phases 执行NGX_HTTP_POST_READ_PHASENGX_HTTP_CONTENT_PHASE之间的阶段
产生应答并调用过滤器链

当请求生成所有输出或出错时
调用ngx_http_finalize_request
若出错,查找错误页并应答
若应答没发完,则激活ngx_http_writer完成后续发送

当应答发送完,销毁请求时
调用ngx_http_finalize_connection()
如果客户端启用keepalive
调用ngx_http_set_keepalive销毁当前请求,并等待下一请求 若未启用,则调用ngx_http_close_request()销毁请求和连接

request

Text Only
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 每个客户端请求均会创建`ngx_http_request_t`  
# ngx_http_request_t`成员如下: 
connection 客户端连接对象,指向`ngx_connection_t`  
    若干请求可引用相同连接一个主请求和若干子请求<br>连接删除后可新建
ctx HTTP模块上下文数组, `NGX_HTTP_MODULE`类型模块可以往驻足存数据  
     ngx_http_get_module_ctx(r, module) 读取模块上下文ngx_http_set_ctx(r, c, module) 添加模块山下文
main_conf
srv_conf
loc_conf
read_event_handler
write_event_handler
ngx_http_request_handler
cache 缓存上游应答数据
upstream 请求上游代理
pool 为请求分配的内存池
header_in 存储读到的HTTP请求头
headers_in 输入HTTP头部对象 
headers_out 输出HTTP头部对象
request_body 客户端请求消息体
start_sec
start_msec 请求创建时间
method
method_name 请求方法
http_protocol 客户端HTTP版本原始字串
http_version 客户端HTTP版本
http_major
http_minor
request_line 请求行
unparsed_uri
uri, args, exten|
main
parent
postponed
phase_handler 请求处理阶段|
ncaptures, captures, captures_data
count
subrequests
uri_changes
blocked
header_only 只发送头部标识|
keepalive 保活标志
header_sent
internal 内部请求标志,请求重定向或子请求可进去该阶段
allow_ranges
subrequest_ranges
single_range
filter_need_temporary

keepalive

tcp长连接 content-length带长度 chunked带长度, 否则等到socket关闭则结束

pipe

一次发送多个请求

lingering_close

先关写socket,等待内核发送缓存区数据发送完,再关闭读socket 若读缓存区无数据,发送完数据后关闭socket; 若读缓存区有数据,则直接发送rst给客户端断开链接