Nginx 只允许 root 和 api 位置

Nginx allow only root and api locations

我有一个服务器配置为我的服务器的反向代理。我想拒绝除两个位置之外的所有请求,一个用于 root,另一个用于 api root。

所以服务器应该只允许对给定路径的请求

example.com/ (only the root)
example.com/api/ (every url after the api root)

预期的行为是服务器应拒绝以下所有可能性。

example.com/location
example.com/location/sublocation
example.com/dynamic-location

我当前的 nginx 配置,

server {

   # server configurations

   location / {

        # reverse proxy configurations

    }

}

如何设置此配置?

这里是:

   location = / {
        # would serve only the root
        # ...
    }

    location /api/ {
        # would serve everything after the /api/
        # ...
    }

您需要一个特殊的“=”修饰符才能使根位置按预期工作

来自docs

Using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison.

您可以使用 if 语句来测试 $request_uri 是否等于 root,或者从 /api/ 开始,所有这些都在同一个 location 语句中,或者在server 上下文:

if ($request_uri !~ ^/$|^/api/) {return 403;}

然而,或者,由于处理的方式,nginx 最有效的方法是有 3 个单独的 location 指令,每个指令处理 3 种可能性中的一种 - /根完全匹配,/api/ 前缀,然后是所有其他内容,根据 http://nginx.org/r/location.

此外,如果您还要求根位置禁止查询字符串,您可以测试$is_args (or $args/$query_string as appropriate), or, outright test whether the whole request URL is exactly / or whether it has anything more to it (note that location directives themselves don't operate based on $request_uri, but based on $uri,两者略有不同。

location = / {
    # handle root
    if ($request_uri != "/") {
        # ensure $query_string and $is_args are not allowed
        return 403 "<h1>403: query_string not allowed</h1>\n";
    }
}
location /api/ {
    # handle the /api/ prefix
}

location / {
    # handle everything else
    return 403;
}