问题原文
原帖链接 · mahyard · CC BY-SA 3.0
I cannot debug this piece of nginx configuration:
I want to add some headers to all requests for a .pdf file
Then I want to remove a token which I add to my veiw directory to avoid unwanted browser's cache:
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;
...
}
There is no nginx syntax error but requesting a .pdf for shows a 404 not found error means that rewrite doesn't apply on the request.
Any help is very appreciated
Thank you
已采纳解答
原帖链接 · Richard Smith · CC BY-SA 3.0
When nginx chooses a location to process a request, it may choose the inner or outer location block. It does not combine the statements from both.
The rewrite is not inherited by the nested location. If you want the rewrite to apply to all locations, you should place it in server block scope.
The regular expression of your rewrite statement is sufficiently specific, that it can be moved as is.
For example:
rewrite "^/static[0-9]{10}/(.*)$" /static/$1 last;
location /static {
location ~* \.pdf$ {
add_header Access-Control-Allow-Origin *;
add_header Content-Disposition 'inline';
}
...
}
Of course, it may be more efficient to just repeat the rewrite statement in both location blocks.
An alternative approach is to avoid the rewrite altogether and use a regular expression location to remove the anti-cache token by using an alias directive. See this document for more.
For example:
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';
}
...
}
Note that regular expression location block have a different evaluation order to prefix location blocks. See this document for details.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
