添加 header 到 nginx 位置指令中的响应

add header to response in nginx location directive

我尝试将响应 header 添加到仅服务的一个位置路径,并且 nginx 配置看起来像

server {
    ...
    add_header x-test test;
    location /my.img {
        rewrite ^/my.img$ /119.img;
        add_header x-amz-meta-sig 1234567890abcdef;
    }
}

但只有top-level header (x-test)有效,location指令中的那个没有出现

$ curl -v -o /tmp/test.img 'https://www.example.com/my.img'
< HTTP/1.1 200 OK
< Server: nginx/1.9.3 (Ubuntu)
< Date: Sun, 14 May 2017 23:58:08 GMT
< Content-Type: application/octet-stream
< Content-Length: 251656
< Last-Modified: Fri, 03 Mar 2017 04:57:47 GMT
< Connection: keep-alive
< ETag: "58b8f7cb-3d708"
< x-test: test
< Accept-Ranges: bytes
< 
{ [16104 bytes data]

如何仅为所服务的特定文件发回自定义 headrr。

rewrite语句是一个隐含的rewrite...last,这意味着最终的URI /119.img不被这个location块处理。在计算响应 headers 时,nginx 位于不同的 location 块中。

您可以尝试使用 rewrite...break 语句从同一位置块中处理最终 URI。有关详细信息,请参阅 this document

location = /my.img {
    root /path/to/file;
    rewrite ^ /119.img break;
    add_header x-amz-meta-sig 1234567890abcdef;
}

如果 location 只匹配一个 URI,请使用 = 格式。有关详细信息,请参阅 this document

另请注意,此 location 块中存在 add_header 语句,这意味着将不再继承外部语句。有关详细信息,请参阅 this document。 :