「零拷贝」这四个字是 nginx 文档里最容易被误读的一个词。
sendfile 并没有消灭内核里的那次拷贝 —— 它消灭的是用户态的往返。
把这一点搞清楚,剩下的 aio、directio、sendfile_max_chunk
全都是这条主线的注脚。读完之后你应该能回答:
sendfile on省掉了哪一次拷贝?没省掉的那次是谁做的?- 为什么
aio on和sendfile on在静态文件上互斥?什么时候 aio 反而不划算?directio打开后,sendfile为什么会自动失效?try_files落在请求处理链的哪一步?它和ngx_http_static_handler谁先谁后?- 同一个文件,nginx 直接发和反代转发,快差在哪?
本文所有行号基于 /work/ai/cwork/nginx,
版本是 nginx 1.31.11(mainline,HEAD e76b6746c)。
13.1 静态文件的三个模块
发静态文件这件事,nginx 分给三个模块干,各占一个 phase:
| 模块 | 源文件 | 挂载的 phase | 干什么 |
|---|---|---|---|
ngx_http_static_module |
src/http/modules/ngx_http_static_module.c |
NGX_HTTP_CONTENT_PHASE |
URI 直接映射成文件,发出去 |
ngx_http_index_module |
src/http/modules/ngx_http_index_module.c |
NGX_HTTP_CONTENT_PHASE |
URI 以 / 结尾时,试 index.html 之类 |
ngx_http_autoindex_module |
src/http/modules/ngx_http_autoindex_module.c |
NGX_HTTP_CONTENT_PHASE |
目录没 index 就列个表 |
三者的挂载方式一模一样 —— 都是 postconfiguration 里往 phase 的
handler 数组尾部 push 一个函数。静态模块的 ngx_http_static_init()
在 src/http/modules/ngx_http_static_module.c:281-297:
// src/http/modules/ngx_http_static_module.c:281-297
static ngx_int_t
ngx_http_static_init(ngx_conf_t *cf)
{
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_static_handler;
return NGX_OK;
}
autoindex 的 ngx_http_autoindex_init() 在src/http/modules/ngx_http_autoindex_module.c:1058-1074,形状完全一致。
同一 phase 里,handler 的执行顺序 = 模块的注册顺序,
也就是auto/modules里ngx_module_order的顺序。
在auto/modules:171-177那张单子里,ngx_http_static_module
排在ngx_http_autoindex_module和ngx_http_index_module前面。也就是说:static 先试,autoindex 次之,index 最后。
这个顺序有讲究 —— index 要读目录里的index.html,
autoindex 要读整个目录,两者都比 static 贵,
所以 static 放在最前面做最便宜的尝试。但要注意:static 遇到 URI 以
/结尾就直接NGX_DECLINED
(src/http/modules/ngx_http_static_module.c:67-69),
所以正常情况下 static 和后面两个不会打架。
13.2 静态请求走过的路
ngx_http_static_handler() 的骨架很短。开头两行就是两道闸门
(src/http/modules/ngx_http_static_module.c:63-69):
// src/http/modules/ngx_http_static_module.c:63-69
if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD|NGX_HTTP_POST))) {
return NGX_HTTP_NOT_ALLOWED;
}
if (r->uri.data[r->uri.len - 1] == '/') {
return NGX_DECLINED;
}
然后是核心三步:
请求 URI
│
▼
┌───────────────────┐
│ ngx_http_map_uri_ │ URI → 文件系统路径
│ to_path() │ (root/alias 拼接)
└────────┬──────────┘
│ path
▼
┌───────────────────┐
│ ngx_open_cached_ │ 打开文件;这一步可以走
│ file() │ open file cache(见第 14 章)
└────────┬──────────┘
│ of.fd, of.size, of.mtime
▼
┌───────────────────┐
│ 组装 ngx_buf_t │ b->in_file = 1
│ │ b->file_pos = 0
└────────┬──────────┘ b->file_last = of.size
│ 一个 in_file 的 buf
▼
┌───────────────────┐
│ ngx_http_output_ │ 进 filter 链
│ filter() │
└────────┬──────────┘
▼
┌───────────────────┐
│ ngx_output_chain │ 决定:直接给 socket?
│ (copy filter) │ 还是先读进用户态内存?
└────────┬──────────┘
▼
┌───────────────────┐
│ ngx_write_filter │ 真正 write/sendfile
└───────────────────┘
从 ngx_open_cached_file() 出来之后,静态模块要的东西都装在ngx_open_file_info_t 里。填这个结构体的代码在src/http/modules/ngx_http_static_module.c:88-97:
// src/http/modules/ngx_http_static_module.c:88-97
clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
ngx_memzero(&of, sizeof(ngx_open_file_info_t));
of.read_ahead = clcf->read_ahead;
of.directio = clcf->directio;
of.valid = clcf->open_file_cache_valid;
of.min_uses = clcf->open_file_cache_min_uses;
of.errors = clcf->open_file_cache_errors;
of.events = clcf->open_file_cache_events;
注意 of.directio 和 of.valid —— 前者决定这次打开要不要
挂 O_DIRECT,后者是 open file cache 的有效期。
这两个字段分别连到第 13.4 节和第 14 章。
组装 buf 的代码在 src/http/modules/ngx_http_static_module.c:261-277:
// src/http/modules/ngx_http_static_module.c:261-277
b->file_pos = 0;
b->file_last = of.size;
b->in_file = b->file_last ? 1 : 0;
b->last_buf = (r == r->main) ? 1 : 0;
b->last_in_chain = 1;
b->sync = (b->last_buf || b->in_file) ? 0 : 1;
b->file->fd = of.fd;
b->file->name = path;
b->file->log = log;
b->file->directio = of.is_directio;
out.buf = b;
out.next = NULL;
return ngx_http_output_filter(r, &out);
坑:
b->in_file = 1只是一个声明 ——
「这个 buf 的内容在文件里,从file_pos到file_last,
别把它当内存数据读」。
真正决定「走 sendfile 还是先读进内存」的,是下一层的ngx_output_chain_as_is()。声明和决策不是一回事,
混了这两层就说不清 sendfile 到底在哪生效。
13.3 sendfile 到底省了什么
13.3.1 两次拷贝的对照
用 read() + write() 发一个文件,数据要过两遍用户态:
page cache
│
│ (1) 拷进用户态 buffer ← read()
▼
用户态 buffer
│
│ (2) 从用户态 buffer 拷出 ← write()
▼
socket buffer
│
▼
网卡
sendfile() 把这两步合成一个系统调用,数据从不进用户态:
page cache
│
│ (1) 内核内部直接搬进 socket
▼
socket buffer
│
▼
网卡
man 2 sendfile 的原话是:
Because this copying is done within the kernel, sendfile() is more
efficient than the combination of read(2) and write(2), which would
require transferring data to and from user space.
所以「省掉的是什么」这句话,准确的答法是:
省掉的是数据在用户态的一次往返(两次用户态拷贝 + 两次系统调用)。
内核内部那次拷贝(page cache → socket buffer)依然存在。
在 Linux 上,page cache → socket buffer 那一次即使有了 sendfile
也要做 —— 真正的零拷贝(page cache 直接挂到 socket 上)需要splice(2),nginx 至今没用它。
一句话:
sendfile是「少进一次用户态」,不是「少拷一次数据」。
说 sendfile 省掉了内核拷贝,是错的。
13.3.2 sendfile 在 nginx 里怎么开关
指令定义在 src/http/ngx_http_core_module.c:404-418:
// src/http/ngx_http_core_module.c:404-418
{ ngx_string("sendfile"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF
|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_core_loc_conf_t, sendfile),
NULL },
{ ngx_string("sendfile_max_chunk"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_core_loc_conf_t, sendfile_max_chunk),
NULL },
对应字段在 ngx_http_core_loc_conf_t 里
(src/http/ngx_http_core_module.h:370 和 :403):
// src/http/ngx_http_core_module.h:370-370
size_t sendfile_max_chunk; /* sendfile_max_chunk */
// src/http/ngx_http_core_module.h:403-403
ngx_flag_t sendfile; /* sendfile */
默认值在 merge 阶段定(src/http/ngx_http_core_module.c:3958-3960):
// src/http/ngx_http_core_module.c:3958-3960
ngx_conf_merge_value(conf->sendfile, prev->sendfile, 0);
ngx_conf_merge_size_value(conf->sendfile_max_chunk,
prev->sendfile_max_chunk, 2 * 1024 * 1024);
sendfile 默认是关的,sendfile_max_chunk 默认 2MB。
sendfile 不是全局开关 —— 它会被拷进连接对象。ngx_http_update_location_config() 里做这件事
(src/http/ngx_http_core_module.c:1370-1376):
// src/http/ngx_http_core_module.c:1370-1376
if ((ngx_io.flags & NGX_IO_SENDFILE) && clcf->sendfile) {
r->connection->sendfile = 1;
} else {
r->connection->sendfile = 0;
}
注意第一个条件:NGX_IO_SENDFILE。这个宏是编译期探测的
—— 编译 nginx 时系统的 sendfile(2) 能不能用。
不能用的话,ngx_io.flags 里就没有这个位,sendfile on 是死指令。
copy filter 随后把它交给输出链
(src/http/ngx_http_copy_filter_module.c:116):
// src/http/ngx_http_copy_filter_module.c:116-116
ctx->sendfile = c->sendfile;
13.3.3 决策点:ngx_output_chain_as_is()
真正判断「这个 buf 能不能不碰用户态」的函数是ngx_output_chain_as_is(),在 src/core/ngx_output_chain.c:264-289:
// src/core/ngx_output_chain.c:264-289
sendfile = ctx->sendfile;
#if (NGX_SENDFILE_LIMIT)
if (buf->in_file && buf->file_pos >= NGX_SENDFILE_LIMIT) {
sendfile = 0;
}
#endif
#if !(NGX_HAVE_SENDFILE_NODISKIO)
/*
* With DIRECTIO, disable sendfile() unless sendfile(SF_NOCACHE)
* is available.
*/
if (buf->in_file && buf->file->directio) {
sendfile = 0;
}
#endif
if (!sendfile) {
这一段里有三道闸门,逐一关掉 sendfile:
| 闸门 | 条件 | 现代 Linux 上生效吗 |
|---|---|---|
NGX_SENDFILE_LIMIT |
文件偏移超过该宏的值 | 不生效 —— 宏压根没被定义(见下) |
NGX_HAVE_SENDFILE_NODISKIO |
buf->file->directio 为真 |
生效 —— Linux 没有这个宏 |
ctx->need_in_memory |
某个 filter 要求内容在内存里 | 生效,比如 gzip |
第二道闸门(directio)在第 13.5 节细说。
第一道是个同名宏的两份定义的坑,值得说清楚。
NGX_SENDFILE_LIMIT 在这棵树里有两个定义:
// src/core/ngx_output_chain.c:13-15
#if 0
#define NGX_SENDFILE_LIMIT 4096
#endif
这一个从加进来那天起就被 #if 0 关着(nginx 0.1.9 那次提交f69060481 就是这么引进来的),值 4096 是历史包袱。
但它不是唯一一份 —— Linux 的平台头文件里还有一份:
// src/os/unix/ngx_linux_config.h:78-83
#if (NGX_HAVE_SENDFILE64)
#include <sys/sendfile.h>
#else
extern ssize_t sendfile(int s, int fd, int32_t *offset, size_t size);
#define NGX_SENDFILE_LIMIT 0x80000000
#endif
这份的语义清楚了:只有当系统没有 sendfile64() 时才定义,
值 0x80000000 就是 2GB —— 因为那台机器上的 sendfile()
用的是 int32_t 偏移(见上面那个 extern 声明),
2GB 以外的文件它根本表达不出来。
而 NGX_HAVE_SENDFILE64 是 configure 时探测出来的
(auto/os/linux:154-168,跑一小段 sendfile() 看能不能用)。
现代 Linux 都有 sendfile64(),所以走的是 #if 那一支 ——NGX_SENDFILE_LIMIT 根本没被定义。
坑:C 预处理器里,
#if (未定义的宏)等价于#if (0)。
所以「这个宏没定义」和「这个宏的值是 0」在效果上是一回事,ngx_output_chain.c里那几处#if (NGX_SENDFILE_LIMIT)
的分支在现代 Linux 上根本不参与编译。你
grep -rn NGX_SENDFILE_LIMIT src/会看到十几处,
但在现代 Linux 的二进制里,它们一条都没生效。
读这种平台条件代码,一定要先问「这个宏在我这台机器上定义了吗」。
那 2GB 的限制在现代 Linux 上由谁管?由 NGX_SENDFILE_MAXSIZE 管
(src/os/unix/ngx_linux_sendfile_chain.c:46),值 2147483647L。
原因写在同文件的注释里(src/os/unix/ngx_linux_sendfile_chain.c:40-44):
Linux 2.6.16 之后 sendfile() 会悄悄把 count 参数截到 2G 减一页大小,
哪怕你在 64 位平台上。所以 nginx 自己先把这个上限算出来,
在 src/os/unix/ngx_linux_sendfile_chain.c:70-74 那里钳位。
注意这两个 2GB 是不同的东西:NGX_SENDFILE_LIMIT 是「关掉 sendfile」的闸门(按文件偏移),NGX_SENDFILE_MAXSIZE 是「一次调用搬多少字节」的上限(按字节数),
后者不会让 sendfile 失效,只是把大文件切成多次调用。
而 NGX_HAVE_SENDFILE_NODISKIO 指的是 sendfile(SF_NODISKIO) 这个标志。
FreeBSD 有它,Linux 没有(auto/os/freebsd:50 是唯一定义它的地方)。
Linux 上如果拿 O_DIRECT 的 fd 去 sendfile,
读出来的内容是绕过 page cache 的、和文件内容可能不一致的
(文件正在被直接写盘,page cache 里是旧数据)——
所以 nginx 直接把 sendfile 关掉,宁可走「读进内存」这条路。
一旦 sendfile 被关掉,as_is() 就返回 0,ngx_output_chain() 会调用 ngx_output_chain_copy_buf()
把文件内容读进用户态 buffer(src/core/ngx_output_chain.c:514-545):
// src/core/ngx_output_chain.c:514-545
size = ngx_buf_size(src);
size = ngx_min(size, dst->end - dst->pos);
sendfile = ctx->sendfile && !ctx->directio;
#if (NGX_SENDFILE_LIMIT)
if (src->in_file && src->file_pos >= NGX_SENDFILE_LIMIT) {
sendfile = 0;
}
#endif
if (ngx_buf_in_memory(src)) {
ngx_memcpy(dst->pos, src->pos, (size_t) size);
src->pos += (size_t) size;
dst->last += (size_t) size;
if (src->in_file) {
if (sendfile) {
dst->in_file = 1;
dst->file = src->file;
dst->file_pos = src->file_pos;
dst->file_last = src->file_pos + size;
} else {
dst->in_file = 0;
}
src->file_pos += size;
注意这里 sendfile = ctx->sendfile && !ctx->directio ——ctx->directio 是输出链自己的标志位,跟 buf->file->directio
是两个东西。ctx->directio 在 ngx_output_chain_align_file_buf()
里被置位(src/core/ngx_output_chain.c:390),表示
「这次要按 O_DIRECT 的对齐要求准备用户态 buffer」。
13.3.4 sendfile_max_chunk:为什么要切块
sendfile_max_chunk 默认 2MB,它限制的是一次写事件里最多发多少字节。
写 filter 在算 limit 的地方用它(src/http/ngx_http_write_filter_module.c:284-292):
// src/http/ngx_http_write_filter_module.c:284-292
if (clcf->sendfile_max_chunk
&& (off_t) clcf->sendfile_max_chunk < limit)
{
limit = clcf->sendfile_max_chunk;
}
} else {
limit = clcf->sendfile_max_chunk;
}
这个 limit 一路传到 c->send_chain(),Linux 上就是ngx_linux_sendfile_chain()(src/os/unix/ngx_linux_sendfile_chain.c:49)。
它内部还有个硬上限(src/os/unix/ngx_linux_sendfile_chain.c:72-74):
// src/os/unix/ngx_linux_sendfile_chain.c:72-74
if (limit == 0 || limit > (off_t) (NGX_SENDFILE_MAXSIZE - ngx_pagesize)) {
limit = NGX_SENDFILE_MAXSIZE - ngx_pagesize;
}
为什么要切块? 一个 10GB 的文件如果一次 sendfile 到底,
这个 worker 就被占住 10GB 的传输时间,期间它服务的其他连接全部饿死。
切块的语义是:发 2MB 就让出 worker,去处理别的连接,
下次写事件再接着发。
limit_rate 也会跟它交互 —— 限速时 limit 取min(sendfile_max_chunk, 速率算出来的量)。
13.4 aio:什么时候反而不划算
13.4.1 aio 的两个实现
aio 指令在 src/http/ngx_http_core_module.c:426-432:
// src/http/ngx_http_core_module.c:426-432
{ ngx_string("aio"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_http_core_set_aio,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_http_core_set_aio()(src/http/ngx_http_core_module.c:4881)
解析三种取值:
| 取值 | 常量 | 实现 | 平台要求 |
|---|---|---|---|
off |
NGX_HTTP_AIO_OFF |
同步 pread() |
无 |
on |
NGX_HTTP_AIO_ON |
Linux 原生 AIO(io_submit) |
NGX_HAVE_FILE_AIO |
threads |
NGX_HTTP_AIO_THREADS |
线程池里 pread() |
NGX_THREADS |
on 的实现在 src/os/unix/ngx_linux_aio_read.c。ngx_file_aio_read() 的核心是填一个 iocb 然后 io_submit
(src/os/unix/ngx_linux_aio_read.c:96-117):
// src/os/unix/ngx_linux_aio_read.c:96-117
ngx_memzero(&aio->aiocb, sizeof(struct iocb));
aio->aiocb.aio_data = (uint64_t) (uintptr_t) ev;
aio->aiocb.aio_lio_opcode = IOCB_CMD_PREAD;
aio->aiocb.aio_fildes = file->fd;
aio->aiocb.aio_buf = (uint64_t) (uintptr_t) buf;
aio->aiocb.aio_nbytes = size;
aio->aiocb.aio_offset = offset;
aio->aiocb.aio_flags = IOCB_FLAG_RESFD;
aio->aiocb.aio_resfd = ngx_eventfd;
ev->handler = ngx_file_aio_event_handler;
piocb[0] = &aio->aiocb;
if (io_submit(ngx_aio_ctx, 1, piocb) == 1) {
ev->active = 1;
ev->ready = 0;
ev->complete = 0;
return NGX_AGAIN;
}
IOCB_FLAG_RESFD + ngx_eventfd 是关键:内核读完之后往 eventfd 里
写一个 8 字节的计数,epoll 那边就醒了。这套机制叫
io_uring 之前的老派异步 I/O。
13.4.2 aio 和 sendfile 为什么互斥
看 copy filter 里 aio 的挂载点
(src/http/ngx_http_copy_filter_module.c:131-135):
// src/http/ngx_http_copy_filter_module.c:131-135
#if (NGX_HAVE_FILE_AIO)
if (ngx_file_aio && clcf->aio == NGX_HTTP_AIO_ON) {
ctx->aio_handler = ngx_http_copy_aio_handler;
}
#endif
再看 ngx_output_chain_copy_buf() 里 aio 分支的位置
(src/core/ngx_output_chain.c:576-585):
// src/core/ngx_output_chain.c:576-585
#if (NGX_HAVE_FILE_AIO)
if (ctx->aio_handler) {
n = ngx_file_aio_read(src->file, dst->pos, (size_t) size,
src->file_pos, ctx->pool);
if (n == NGX_AGAIN) {
ctx->aio_handler(ctx, src->file);
return NGX_AGAIN;
}
} else
这个分支在 else 里面 —— 它只在「文件内容已经被拷进用户态
buffer 之后」才会被走到。也就是说:
aio 的作用是:把「读文件进用户态」这一步变成异步的。
如果 sendfile 生效,文件内容压根不进用户态,aio 就没有用武之地。
所以 aio on 和 sendfile on 在静态文件上是互斥的,
而且是代码结构决定的,不是配置检查拦的。
坑:网上流传的「
aio on+sendfile on一起开,aio 会让小文件变慢」
—— 对,小文件确实变慢,但原因不是 aio 本身慢,
而是开了 aio 之后 sendfile 这条路就断了。
nginx 官方的建议是:要么纯 sendfile,要么纯 aio,
别指望它们叠加。
13.4.3 aio 什么时候划算、什么时候不划算
| 场景 | aio 划算吗 | 原因 |
|---|---|---|
| 大文件(几百 MB)+ 慢盘/网络盘 | 划算 | 同步 pread() 会把 worker 卡住几秒;aio 让 worker 去干别的 |
| 大文件 + SSD + 已在 page cache | 不划算 | 读本来就是一次内存拷贝,异步的开销(提交 iocb、等 eventfd、重新进事件循环)比读本身还贵 |
| 小文件(几 KB) | 不划算 | 一次 pread() 几微秒,异步的往返开销(系统调用 + 事件循环调度 + 上下文切换)是它的几十倍 |
| 内存已满、page cache 没命中 | 划算 | 同步读要真的去等磁盘 |
核心判断:aio 划算的前提是「这一次读会阻塞,而且阻塞时间足够长,
长到值得付一次事件循环往返」。SSD 上的小文件两条都不满足。
原生 AIO 还有个硬伤:一次 io_submit 只提交一个 iocb
(src/os/unix/ngx_linux_aio_read.c:111 的 io_submit(ngx_aio_ctx, 1, piocb)),
没有批量提交。而且 ngx_file_aio 是个全局开关,io_submit 返回 ENOSYS 时会被永久关掉
(src/os/unix/ngx_linux_aio_read.c:128-131):
// src/os/unix/ngx_linux_aio_read.c:128-131
if (err == NGX_ENOSYS) {
ngx_file_aio = 0;
return ngx_read_file(file, buf, size, offset);
}
所以
aio on在容器里的表现很不稳定:
宿主机内核不支持、或者 seccomp 挡了io_submit,
nginx 会静默退化成同步读 —— 日志里什么也看不出来。
还有一个保护性上限:r->main->blocked >= NGX_HTTP_MAX_BLOCKED
(250,见 src/http/ngx_http_request.h:14)时,
copy filter 会摘掉 aio handler,改成同步读
(src/http/ngx_http_copy_filter_module.c:164-171):
// src/http/ngx_http_copy_filter_module.c:164-171
if (r->main->blocked >= NGX_HTTP_MAX_BLOCKED) {
#if (NGX_HAVE_FILE_AIO)
ctx->aio_handler = NULL;
#endif
#if (NGX_THREADS)
ctx->thread_handler = NULL;
#endif
}
这是防「异步请求堆积到把 worker 拖垮」的兜底。
13.5 directio 与 sendfile 的关系
directio 指令的定义在 src/http/ngx_http_core_module.c:447-453:
// src/http/ngx_http_core_module.c:447-453
{ ngx_string("directio"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_http_core_directio,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_http_core_directio()(src/http/ngx_http_core_module.c:4978)
解析 off 或一个字节数(directio 4k / directio 512):
// src/http/ngx_http_core_module.c:4990-4998
if (ngx_strcmp(value[1].data, "off") == 0) {
clcf->directio = NGX_OPEN_FILE_DIRECTIO_OFF;
return NGX_CONF_OK;
}
clcf->directio = ngx_parse_offset(&value[1]);
if (clcf->directio == (off_t) NGX_ERROR) {
return "invalid value";
}
directio 的语义:绕过 page cache,直接读写磁盘。
适合「文件比内存还大、且不想被 cache 污染」的场景。
O_DIRECT 有个硬约束:用户态 buffer 的地址、长度、
文件偏移都得按扇区对齐。nginx 在两处处理这件事:
- 打开文件时挂标志位 ——
ngx_open_and_stat_file()
(src/core/ngx_open_file_cache.c:922-930):
// src/core/ngx_open_file_cache.c:922-930
if (of->directio <= ngx_file_size(&fi)) {
if (ngx_directio_on(fd) == NGX_FILE_ERROR) {
ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
ngx_directio_on_n " \"%V\" failed", name);
} else {
of->is_directio = 1;
}
}
- 分配用户态 buffer 时按
directio_alignment对齐 ——ngx_output_chain_get_buf()里用ngx_pmemalign()
(src/core/ngx_output_chain.c:471-479)。
回到 sendfile:前面说过,O_DIRECT 的 fd 不能 sendfile
(Linux 没有 SF_NODISKIO)。所以ngx_output_chain_as_is() 里有这么一段
(src/core/ngx_output_chain.c:277-284):
// src/core/ngx_output_chain.c:277-284
/*
* With DIRECTIO, disable sendfile() unless sendfile(SF_NOCACHE)
* is available.
*/
if (buf->in_file && buf->file->directio) {
sendfile = 0;
}
于是 directio on + sendfile on 的组合,实际行为是:
directio 赢了,sendfile 被自动降级。文件内容被读进
对齐的用户态 buffer,再 write 出去。
坑:这一点经常被忽略。很多人配了
sendfile on; directio 4k;以为两个都在生效,
实际上directio一开,sendfile就形同虚设了。
想要两个都生效,得确认平台支持SF_NODISKIO(FreeBSD),
或者干脆别同时开。
directio_alignment 默认 512 字节
(src/http/ngx_http_core_module.c:3974-3975):
// src/http/ngx_http_core_module.c:3974-3975
ngx_conf_merge_off_value(conf->directio_alignment, prev->directio_alignment,
512);
13.6 try_files 落在哪
try_files 不在 ngx_http_core_module.c 里 —— 它是独立模块src/http/modules/ngx_http_try_files_module.c。
它在 NGX_HTTP_PRECONTENT_PHASE(precontent phase),
比 content phase 早一档。ngx_http_try_files_init()
在 src/http/modules/ngx_http_try_files_module.c:404-420:
// src/http/modules/ngx_http_try_files_module.c:404-420
static ngx_int_t
ngx_http_try_files_init(ngx_conf_t *cf)
{
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_PRECONTENT_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_try_files_handler;
return NGX_OK;
}
这就是 try_files 和 static 的先后关系:
rewrite phase
│
▼
precontent phase
└── ngx_http_try_files_handler
│ 逐个候选路径试存在性
│ 命中 → 改写 r->uri → NGX_DECLINED
│ 全不中 → internal_redirect 到最后一个候选
▼
content phase
├── ngx_http_static_handler ← 拿到改写后的 uri,去开文件
├── ngx_http_autoindex_handler
└── ngx_http_index_handler
try_files 自己不发送文件。它的动作是:
探测哪个候选路径存在,然后把 r->uri 改成那个路径,
再 NGX_DECLINED 让 content phase 的 static 接手。
探测存在性用的是同一个 ngx_open_cached_file()
(src/http/modules/ngx_http_try_files_module.c:232-240):
// src/http/modules/ngx_http_try_files_module.c:232-240
ngx_memzero(&of, sizeof(ngx_open_file_info_t));
of.read_ahead = clcf->read_ahead;
of.directio = clcf->directio;
of.valid = clcf->open_file_cache_valid;
of.min_uses = clcf->open_file_cache_min_uses;
of.test_only = 1;
of.errors = clcf->open_file_cache_errors;
of.events = clcf->open_file_cache_events;
of.test_only = 1 是关键 —— 它告诉ngx_open_cached_file():「我只想知道这个路径在不在,
不要真的打开文件」。实现见src/core/ngx_open_file_cache.c:161-181:走ngx_file_info_wrapper() 拿 stat 信息就返回,
不调 open()。
坑:
try_files和 open file cache 配合时,test_only的那次探测也会填缓存
(存的是元信息,fd 是NGX_INVALID_FILE)。
所以try_files $uri $uri/ =404这种写法,
每个请求会做两次 open file cache 查找
(一次 test_only 探测,一次 static 真正打开)。
命中缓存时第二次是廉价的;但如果 open file cache 没开
或者条目已过期,就是两次 stat。
13.7 静态文件为什么比反代快
同一个文件,nginx 直接发 vs 反代转发,差距在四个地方:
| 环节 | 直接发静态文件 | 反代 |
|---|---|---|
| 上游连接 | 无 | 要建连、握手、可能要等 keepalive 复用 |
| 数据经过用户态次数 | 0 次(sendfile 生效时) | 至少 2 次(上游 socket → nginx buffer → 客户端 socket) |
| 协议解析 | 无 | nginx 要完整解析上游的 HTTP 响应 |
| 错误面 | 一个文件读不到就是 404 | 上游超时、502、504、连接重置全都有 |
「快」的根源不是 nginx 做了什么魔法,而是少了一整层网络往返。
反代的开销大头在「等上游」和「多两次拷贝」上。
但反代有静态文件做不到的能力:上游能动态生成、能按请求头变化、
能做鉴权、能合并多个源。所以正确的做法不是二选一,
而是在 nginx 前面就把能静态化的部分摘出去。
一个实用的判据:
同一个 URL,
如果它的响应只取决于路径(不取决于 query、header、cookie)
→ 交给 static / try_files
如果响应取决于请求内容
→ 交给 proxy
13.8 小结
- 静态文件由三个模块发:
static/autoindex/index,
都挂在 content phase,static 排最前。 - 静态模块只做三件事:URI → 路径、开文件、组装
in_file的 buf。 - sendfile 省掉的是用户态往返,不是内核拷贝。
内核里 page cache → socket buffer 那一次照旧。 sendfile默认关;生效要在ngx_output_chain_as_is()里
过三道闸门(NGX_SENDFILE_LIMIT、directio、need_in_memory)——
但第一道在现代 Linux 上因为宏没定义而根本不参与编译。sendfile_max_chunk默认 2MB,作用是别让一个大文件
把 worker 占死。- aio 和 sendfile 在静态文件上互斥 —— aio 的作用是
「把读进用户态这一步异步化」,而 sendfile 生效时压根不进用户态。 - aio 只在「读会长时间阻塞」时划算;SSD 上的小文件开 aio 是亏的。
directio打开后 sendfile 自动失效(Linux 没有SF_NODISKIO),
两者不是叠加关系。try_files在 precontent phase,只做存在性探测和 URI 改写,
真正发文件的还是 content phase 的 static。
下一篇讲文件缓存:file cache 缓存什么、open file cache 缓存什么、
两者的 key 怎么算、什么时候会绕过缓存、缓存怎么失效。
参考
- 源码树:
/work/ai/cwork/nginx(nginx 1.31.11,HEADe76b6746c) - 主要落点:
src/http/modules/ngx_http_static_module.c—— 静态文件处理src/http/modules/ngx_http_try_files_module.c—— try_filessrc/http/ngx_http_core_module.c—— sendfile / aio / directio 指令src/core/ngx_output_chain.c—— 输出链,sendfile 与 aio 的决策点src/os/unix/ngx_linux_sendfile_chain.c—— Linux sendfile 实现src/os/unix/ngx_linux_aio_read.c—— Linux 原生 AIO 实现
- 系统调用手册:
sendfile(2)、io_submit(2) - 官方文档:ngx_http_core_module
的sendfile/sendfile_max_chunk/aio/directio四节