【问题标题】:Nginx block all traffic with specific custom header except to some urlsNginx 阻止具有特定自定义标头的所有流量,但某些 url 除外
【发布时间】:2021-12-18 13:02:37
【问题描述】:

我有一项托管在内部网络中的服务,该服务在自定义负载均衡器后面的端口 443(通过 https)中接收来自互联网和内部网络的流量。

内部网络请求带有一个额外的自定义标头,我们称之为X-my-lb-header。

我想阻止所有 uri 的所有外部传入流量(返回一个 http 响应代码),某些特定的除外。

例如,假设我想允许到达两个端点 /endpoind1/(前缀匹配)和 /endpoint2 实际匹配的流量。

实现这种行为的最佳方法是什么?

如果我的理解是正确的,我需要类似(下面的语法不正确)

   location = /endpoind2 {
        if ($http_x_my_lb_header not exists) {
            pass
        } else {
            return 404
        }
        ... the rest of the directives
    }


   location ~ / {
        if ($http_x_my_lb_header) {
            return 404;
        }
        ... the rest of the directives
    }

但是由于 nginx 不支持 else ,所以我想不通。

有什么想法吗?

【问题讨论】:

  • 您的示例中根本不需要else。将if ($http_x_my_lb_header) { return 404; } 放在location 块的开头将阻止没有X-my-lb-header 的所有流量。但据我了解,您需要相反的东西?
  • @IvanShatsky 确实我需要相反的。如果标头存在不要阻塞或说不同,如果标头不存在则阻塞。

标签: nginx networking nginx-config


【解决方案1】:

所以你需要一些类似的逻辑

if (header exists) {
    if (request URI isn't whitelisted) {
        block the request
    }
}

或者换句话说

if ((header exists) AND (request URI isn't whitelisted)) {
    block the request
}

好吧,nginx 不允许嵌套 if 块(也不允许逻辑条件)。虽然有些人发明了一个非常奇怪但有创意的解决方案,例如 this one(模拟 AND)甚至 this one(模拟 OR),但大部分此类问题可以使用 map 块(一个非常强大的 nginx 功能)来解决.

这是一个例子:

# get the $block variable using 'X-my-lb-header' value
map $http_x_my_lb_header $block {
    # if 'X-my-lb-header doesn't exists, get the value from another map block
    ''    $endpoint;
    # default value (if the 'X-my-lb-header' exists) will be an empty string
    # (unless not explicitly defined using 'default' keyword)
}

# get the $endpoint variable using request URI
map $uri $endpoint {
    # endpoint1 prefix matching (using regex)
    ~^/endpoint1    ''; don't block
    # endpoint2 exact matching
    /endpoint2      ''; don't block
    default         1; # block everything other
}

现在您可以在您的服务器块中使用此检查(不要将其放在某个位置,在 server 上下文中使用):

if ($block) { return 404; }

【讨论】:

  • 这非常有用。我想我可以使用地图功能来实现它。谢谢伊万。
猜你喜欢
  • 2019-11-09
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2018-07-14
  • 2021-08-26
  • 2020-09-16
  • 1970-01-01
相关资源
最近更新 更多