Nginx:如何仅向特定文件和文本添加标头

Mac*_*aca 5 nginx

我有多个 url 需要使用 nginx 添加相同的标头集。这是文件名。

File Group1
    https://www.example.com/news/2017-08-03/article-xyz/
    https://www.example.com/news/2017-08-03/article-xyz/topics/
    https://www.example.com/news/2017-08-03/article-xyz/gallery/

File Group2
    https://www.example.com/news/2017-08-02/article-abc/
    https://www.example.com/news/2017-08-02/article-abc/topics/
    https://www.example.com/news/2017-08-02/article-abc/gallery/
Run Code Online (Sandbox Code Playgroud)

因此在这种情况下 File Group1 需要:

add_header Cache-Tag  article-xyz;
Run Code Online (Sandbox Code Playgroud)

文件组2需要:

add_header Cache-Tag  article-abc;
Run Code Online (Sandbox Code Playgroud)

所以 nginx.conf 应该是这样的

  location /news/ {
        add_header Cache-Tag  article-abc;
    }
Run Code Online (Sandbox Code Playgroud)

但是我如何在添加标头中动态应用它呢?

Ric*_*ith 5

map一种解决方案是对值使用指令$request_uri。例如:

map $request_uri $cache_tag {
    default        "";
    ~/article-xyz/ "article-xyz";
    ~/article-abc/ "article-abc";
}
server {
    ...
    add_header Cache-Tag $cache_tag;
    ...
}
Run Code Online (Sandbox Code Playgroud)

map街区位于server街区之外(如图所示)。该add_header语句可以位于最终处理请求的server作用域或块中location(遵循继承规则)。有关详细信息,请参阅

不要在map指令中使用捕获,因为它不起作用。