为某些 request_uri 添加 header

Ann*_*hri 3 nginx

该应用程序处理所有路由。所以这个基本配置块是有效的:

location / {
    try_files $uri $uri/ /index.html;
}
Run Code Online (Sandbox Code Playgroud)

问题是我想在访问者请求某个 URI 时添加自定义标头。例如,/content。嗯,这一定很简单:

location ~ ^/content {
   try_files $uri $uri/ /index.html;
   add_header X-CUSTOM-HEADER value;
}
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。Nginx 没有创建该标头。然后,我尝试try_files内容块中删除该指令,但这显然不起作用,因为/content根目录中没有“真实”文件夹。因此,nginx 将抛出404 not found错误。

我还尝试将该块移动到根位置块内。也不工作。


在 Apache 中,可以使用以下命令轻松完成此操作:

<If "%{THE_REQUEST} =~ pattern">
    Header set HEADER value;
</If>
Run Code Online (Sandbox Code Playgroud)

Ric*_*ith 5

您可以使用映射变量设置标头。如果该变量设置为空字符串,则标头将被默默丢弃。

例如:

map $request_uri $myheader {
    ~^/content   a_value;
}
server {
    ...
    add_header X-CUSTOM-HEADER $myheader;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)