嵌套位置无法正常工作

mah*_*ard 5 configuration nginx web-server

我不能调试这块nginx的配置:
我想一些头添加到了所有的请求.pdf文件,
然后我想删除一个令牌,我添加到我的教职员目录,以避免不必要的浏览器缓存:

location /static {
    location ~* \.pdf$ {
        add_header Access-Control-Allow-Origin *;
        add_header Content-Disposition 'inline';
    }
    #Remove Anti cache token
    rewrite "^/static[0-9]{10}/(.*)$" /static/$1 last;
    ...
}
Run Code Online (Sandbox Code Playgroud)

没有 nginx 语法错误,但请求.pdffor 显示 404 not found 错误意味着重写不适用于请求。

非常感谢任何帮助
谢谢

Ric*_*ith 8

nginx选择了一个location要处理的请求时,它可以选择所述内部或外部location块。它没有结合两者的陈述。

rewrite不被嵌套继承location。如果您希望将rewrite应用于所有位置,则应将其放置在server块范围内。

您的rewrite语句的正则表达式足够具体,可以按原样移动。

例如:

rewrite "^/static[0-9]{10}/(.*)$" /static/$1 last;

location /static {
    location ~* \.pdf$ {
        add_header Access-Control-Allow-Origin *;
        add_header Content-Disposition 'inline';
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

当然,只rewrite在两个location块中重复该语句可能更有效。


另一种方法是rewrite完全避免 ,并使用正则表达式location通过使用alias指令删除反缓存令牌。有关更多信息,请参阅此文档

例如:

location ~ "^(?<prefix>/static)[0-9]{10}(?<suffix>/.*)$" {
    alias /path/to/root$prefix$suffix;

    location ~* \.pdf$ {
        add_header Access-Control-Allow-Origin *;
        add_header Content-Disposition 'inline';
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,正则表达式location块与前缀location块的计算顺序不同。有关详细信息,请参阅此文档