$content_type

$content_type 变量在 NGINX 中保存 HTTP 响应的 Content-Type 头的值。 — NGINX Core (HTTP)

$content_type NGINX Core (HTTP)

说明

$content_type 变量在 NGINX 中在处理响应时会被自动设置,用来表示该响应的 Content-Type 头。通常,它用于指示返回资源的媒体类型,遵循 RFC 6838 定义的格式。常见值包括用于 HTML 文档的 'text/html'、用于 JSON 响应的 'application/json' 以及用于 PNG 图像的 'image/png'。 此变量在请求处理阶段被设置,可以被影响响应的各种指令所修改,例如 'add_header'、'default_type' 和 'types'。当 NGINX 提供静态文件时,Content-Type 根据文件扩展名和在 'http' 区块或特定 'server' 或 'location' 上定义的配置设置来确定。例如,如果请求的是扩展名为 '.html' 的文件,$content_type 通常会被设置为 'text/html'。 在未显式设置类型的情况下,如果存在 'default_type' 指令,NGINX 会默认使用该指令提供的值,否则该变量可能保持未设置。

配置示例

location /images/ {
    types {
        image/png png;
        image/jpeg jpg;
        image/gif gif;
    }
    default_type application/octet-stream;
    add_header Content-Type $content_type;
}

子系统

http

可缓存

上下文

http, server, location, if

如果没有匹配的类型,$content_type 可能为空,导致意外的响应。

自定义类型应在 'types' 块中正确声明,以确保 $content_type 被正确分配。

在不处理响应的上下文中使用 $content_type 可能会导致无关的值。