如何避免在 nginx 中重复 add_header 指令?

Cho*_*per 6 nginx http-headers

文档是这样说的:

当且仅当在当前级别上没有定义 add_header 指令时,这些指令才从上一级继承。

我的问题是我有几个location要缓存的块,如下所示:

add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

location ~ ^/img/(.*)\.(png|jpg|jpeg|gif|bmp)$ {
    expires 1w;
    add_header Cache-Control public;
}
Run Code Online (Sandbox Code Playgroud)

但这将使我丢失在块外声明的所有标头。所以显然唯一的方法是在每个位置块上复制这些标题,例如:

add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

location ~ ^/img/(.*)\.(png|jpg|jpeg|gif|bmp)$ {
    expires 1w;
    add_header Cache-Control public;
    add_header X-Frame-Options SAMEORIGIN;
    add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
}
Run Code Online (Sandbox Code Playgroud)

好像不太对 有任何想法吗?

Cra*_*ell 3

您正在寻找 ngx_headers_more 模块: https://www.nginx.com/resources/wiki/modules/headers_more/

是的,add_header 的行为确实令人恼火:)