Nginx:如何添加标题只有特定的文件和文本

我有多个需要添加相同的头集与Nginx的url。 这是文件名。

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/ 

所以在这种情况下,文件组1需要:

 add_header Cache-Tag article-xyz; 

而文件组2需要:

 add_header Cache-Tag article-abc; 

所以nginx.conf应该是这样的

  location /news/ { add_header Cache-Tag article-abc; } 

但是,我怎样才能应用这个dynamic添加标题?

一种解决scheme是在$request_uri值上使用map指令。 例如:

 map $request_uri $cache_tag { default ""; ~/article-xyz/ "article-xyz"; ~/article-abc/ "article-abc"; } server { ... add_header Cache-Tag $cache_tag; ... } 

地图块位于server块之外(如图所示)。 add_header语句可以位于server范围内,也可以位于最终处理请求的location块中(受inheritance规则约束)。 看到这个和这个细节。

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