为什么Nginx不测试所有可用位置?

时间:2019-03-04 13:22:19

标签: nginx

我具有以下Nginx服务器配置:

server {
    error_log   /var/logs/error_stage.log debug;
    root        /var/htdocs_stage/;
    index       index.php index.html;

    # A
    location / {
        try_files $uri $uri/ =404;
    }

    # B
    location ~* \.(txt|xml|js)$ {
        expires 8d;
    }

    # C    
    location /. {
        deny all;
    }

    # D
    location = /wp-config.php {
        deny all;
    }

    # E
    location ~* ^\/wp-content\/.*\.(txt|md|log)$ {
        deny all;
    }
}

然后我请求以下网址:

https://example.com/wp-contents/themes/demo/readme.txt

我希望此请求由位置规则E 处理,并且访问被拒绝。但是nginx实际上应用规则B ,并为文件提供8天的过期缓存!?

在error_stage.log文件中,我找到以下详细信息:

... [debug]: *1396 http uri: "/wp-contents/themes/demo/readme.txt"
...
... [debug]: *1396 generic phase: 0
... [debug]: *1396 rewrite phase: 1
... [debug]: *1396 test location: "/"
... [debug]: *1396 test location: "wp-config.php"
... [debug]: *1396 test location: ~ "\.(txt|xml|js)$"
... [debug]: *1396 using configuration "\.(txt|xml|js)$"

在这里,我注意到nginx仅测试规则A,B和D。在这三个规则中,B是正确的规则。
但是,正如您在我的nginx配置中看到的那样,还有两个甚至没有经过测试的规则...

->我的配置有什么错误?

Btw:error_stage.log文件仅由该特定服务器块使用。因此,我绝对确定,没有其他服务器块可用于处理请求。

1 个答案:

答案 0 :(得分:1)

配置中的“错误”是正则表达式(~)位置的顺序。

NGINX按照配置文件中出现的顺序检查正则表达式的位置。一旦找到匹配的对象,它将立即使用该位置满足请求。这就是它的工作方式。

因此,如果您仅在配置中将位置E移到位置B上方,那么E将是适用位置。

相关问题