覆盖单个位置块的 nginx 拒绝规则

Chr*_*her 6 nginx

我有一个像这样的 nginx 设置,其中服务器应该大部分是私有的(只有某些 IP 地址可以使用该服务器),除了一个location应该公开可用的块:

\n\n
server {\n  listen  443 ssl default;\n\n  # Allow access only from certain IP addresses\n  allow   12.34.56.78/32;\n  allow   10.0.2.2/32;\n  deny    all;\n\n  # Proxy dynamic requests to the app\n  location / {\n    proxy_pass  http://127.0.0.1:8000;\n  }\n  # Serve static assets from disk\n  location = /favicon.ico {\n    alias  /var/www/example.com/htdocs/static/images/favicon.png;\n  }\n  location /static {\n    alias  /var/www/example.com/htdocs/static;\n  }\n  ...\n\n  # Allow public access to this endpoint\n  location = /public/endpoint {\n    proxy_pass  http://127.0.0.1:9000;\n\n    # Allow *all* IPs here, so that they don\'t hit the server "deny" rule\n    # [except this doesn\'t seem to work...]\n    allow 0.0.0.0/0;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,allow在公共location块末尾添加该规则不起作用 \xe2\x80\x94 来自不在上面列表中的 IP 的请求会被拒绝。

\n\n

deny all规则从server块移动到每个非公共location块也没有达到预期的效果。

\n\n

有没有一种方法可以实现所需的行为,而不必将整套“允许、允许、允许、拒绝”规则复制到每个非公共location块中?

\n

pho*_*ops 4

你应该只使用allow all

location = /public/endpoint {
    proxy_pass  http://127.0.0.1:9000;

    # Allow *all* IPs here, so that they don't hit the server "deny" rule
    allow all;
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用不同类型的限制,您可能需要添加satisfy any;才能使其正常工作。