If statement Nginx配置跳过父位置块中的if语句

If statement Nginx配置跳过父位置块中的if语句,if-statement,web,nginx,configuration,reverse-proxy,If Statement,Web,Nginx,Configuration,Reverse Proxy,我有以下设置: location @public { auth_basic off; } location @webdav { proxy_set_header Host $host; proxy_pass http://localhost:8080; } location / { # WebDAV server if ($request_method != GET) { error_page 418 = @webdav;

我有以下设置:

location @public {
    auth_basic off;
}
location @webdav {
    proxy_set_header Host $host;
    proxy_pass http://localhost:8080;
}
location / {
    # WebDAV server
    if ($request_method != GET) {
        error_page 418 = @webdav;
        return 418;
    }
    gzip on;
    fancyindex on;

    location ~ /(public|\.well-known)/ {
        if ($remote_user = "") {
            error_page 418 = @public;
            return 418;
        }
    }
    location = /robots.txt {
        add_header Content-Type text/plain;
        return 200 "User-agent: *\nDisallow: /\n";
    }
}
我想将每个非GET请求重定向到用Go编写的内部WebDAV处理程序。与文件系统的其余部分不同,/public文件夹不需要基本身份验证就可以访问


然而,对于嵌套的位置块,我的父if语句似乎被忽略。在/public上尝试任何非GET请求将导致505,并且在/robots.txt上返回我配置的文本。然而,gzip或fancyindex的情况并非如此,因为/public和robots.txt都是gzip和fancy索引的。

结果表明,问题在于nginx处理块的顺序。首先执行两个嵌套的位置块,然后才执行父位置语句。由于我的嵌套位置块都返回,因此永远不会到达父位置语句。解决方案是将我的WebDAV代码添加到每个嵌套位置块的开头。最终代码:

location @public {
    auth_basic off;
}
location @webdav {
    proxy_set_header Host $host;
    proxy_pass http://localhost:8080;
}
location / {
    # WebDAV server
    if ($request_method != GET) {
        error_page 418 = @webdav;
        return 418;
    }
    gzip on;
    fancyindex on;

    location ~ /(public|\.well-known)/ {
        # WebDAV server
        if ($request_method != GET) {
            error_page 418 = @webdav;
            return 418;
        }
        if ($remote_user = "") {
            error_page 418 = @public;
            return 418;
        }
    }
    location = /robots.txt {
        # WebDAV server
        if ($request_method != GET) {
            error_page 418 = @webdav;
            return 418;
        }
        add_header Content-Type text/plain;
        return 200 "User-agent: *\nDisallow: /\n";
    }
}