位置不适用于文件,仅适用于路径

时间:2018-10-06 21:05:06

标签: nginx nginx-location nginx-config nginx-log

我有一个看起来像这样的nginx.conf:

server {
  ...
  root /var/opt/data/web;
  ...

  location ~* \.(?:eot|woff|woff2|ttf|js)$ {
    expires 1M;
  }

  ...

  location /one {
    root /var/opt/data/alternatives;
    try_files $uri $uri/ =404;
  }

  location /two {
    root /var/opt/data/alternatives;
    try_files $uri $uri/ =404;
  }
}

当我curl http://localhost/one/时,我得到index.html中存储在/other中的内容。但是当我卷曲.../localhost/one/foo.js时,找不到文件,并且在error.log中得到了这个文件:

  

open()“ /default/foo.js”失败(2:无此类文件或目录)

我尝试了location ~ (one|two)location /one/甚至是location ~ /(one|two)之类的其他变体,但是所有的变体都不起作用。

完整的配置由更多location组成,但我想造成问题的原因是我将.js资源设置为expire -1的位置,因为这阻止了更改扎根于我的需求。

如果这很重要:我使用nginx 1.15.2。如果您想知道为什么会有一个奇怪的alternatives目录:web目录是由CMS软件创建的,而alternativesgit pull编辑的。

1 个答案:

答案 0 :(得分:1)

nginx选择一个locationprocess a request。您的location ~* \.(?:eot|woff|woff2|ttf|js)$块处理任何以.js结尾的URI,其root的值将从外部块继承为/var/opt/data/web

在有多个根的情况下,需要使用location修饰符确保这些^~块优先。有关详细信息,请参见this document

例如:

server {
    ...
    root /var/opt/data/web;
    ...    
    location ~* \.(?:eot|woff|woff2|ttf|js)$ {
        expires 1M;
    }    
    ...
    location ^~ /one {
        root /var/opt/data/alternatives;
        try_files $uri $uri/ =404;

        location ~* \.(?:eot|woff|woff2|ttf|js)$ {
            expires 1M;
        }    
    }
    ...
}

如果您需要将expires规则应用于其他根,则需要在该范围内重复location,如上所示。


作为替代,expires指令可以与map结合使用。有关详细信息,请参见this document

例如:

map $request_uri $expires {
    default                            off;
    ~*\.(eot|woff|woff2|ttf|js)(\?|$)  1M;
}
server {
    ...
    root /var/opt/data/web;
    expires $expires;
    ...
    location ^~ /one {
        root /var/opt/data/alternatives;
        try_files $uri $uri/ =404;
    }
    ...
}
相关问题