nginx 可以作为一个 静态资源服务器
我们暴露一个 nginx 服务
然后 从浏览器访问 存储的文件, 图片, 视频, html 等等, nginx 可以正确的 设置 Content-Type 给客户端使用
客户端 识别到了 图片, 自动加载图片, 识别到了 html, 自动渲染 html
识别到了 其他二进制文件, 自动下载文件 等等
我们这里 就来看一下 nginx 是如何响应 Content-Type 的
以下截图, 调试基于 nginx-1.18.0
本文的答案就在这里了
如果上游服务已经设置了 Content-Type, 使用已有的 Content-Type
否则根据 r.uri 的 extension 来尝试获取 Content-Type, clcf->types_hash 中存放了各种后缀 映射的 Content-Type, 如果获取到了, 使用该 Content-Type
否则 使用配置的 默认的Content-Type

请求为 "/regex11.html"
根据 "html" 获取 Content-Type, 拿到的是 "text/html", 响应给客户端
- (gdb) b ngx_http_core_module.c:1616
- Breakpoint 6 at 0x107d247f6: file src/http/ngx_http_core_module.c, line 1616.
- (gdb) print r.uri
- $83 = {len = 13, data = 0x7fa04a000004 "/regex11.html HTTP/1.1\r\nHost"}
- (gdb) list
- 1611
- 1612 }
- 1613
- 1614 type = ngx_hash_find(&clcf->types_hash, hash,
- 1615 r->exten.data, r->exten.len);
- 1616
- 1617 if (type) {
- 1618 r->headers_out.content_type_len = type->len;
- 1619 r->headers_out.content_type = *type;
- 1620
- (gdb) next
- 1617
- (gdb) print type
- $80 = (ngx_str_t *) 0x7fa048017d50
- (gdb) print type.data
- $81 = (u_char *) 0x7fa048017d30 "text/html"
- (gdb) print clcf->default_type
- $82 = {len = 24, data = 0x7fa048018c95 "application/octet-stream"}

来自于 mime.types 的配置文件
- http {
- include mime.types;
- default_type application/octet-stream;
- // xxx
- }
完