大网数据广告活动
服务器运维问答

Nested location doesn't work properly

· 52CE 我爱测

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 { loc…

问题原文

原帖链接 · 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-01-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。