跳转至

loop-detect: CDN-Loop 头支持请求循环防止

安装

您可以在任何基于 RHEL 的发行版中安装此模块,包括但不限于:

  • RedHat Enterprise Linux 7、8、9 和 10
  • CentOS 7、8、9
  • AlmaLinux 8、9
  • Rocky Linux 8、9
  • Amazon Linux 2 和 Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install nginx-module-loop-detect
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install nginx-module-loop-detect

通过在 /etc/nginx/nginx.conf 的顶部添加以下内容来启用模块:

load_module modules/ngx_http_loop_detect_module.so;

本文档描述了 nginx-module-loop-detect v0.1.0,于 2026 年 1 月 6 日发布。


http {
    # 在 location 块中启用模块
    loop_detect on;
    loop_detect_cdn_id my_cdn_id;
    loop_detect_status 508;
    loop_detect_max_allow_loops 10;

    server {
        listen 80;
        server_name example.com;
        location / {
            proxy_set_header CDN-Loop $loop_detect_proxy_add_cdn_loop;
            proxy_pass http://example.upstream.com;
        }
    }
}

指令

loop_detect

语法: loop_detect on | off;

默认值: loop_detect off;

上下文: http, server, location

启用或禁用当前作用域的循环检测。启用时,模块检查 CDN-Loop 头以跟踪跳数,并阻止超过允许限制的请求。

loop_detect_cdn_id

语法: loop_detect_cdn_id string;

默认值: loop_detect_cdn_id openresty;

上下文: http, server, location

设置您集群的唯一标识符。此标识符用于解析和跟踪 CDN-Loop 头中的循环。

loop_detect_status

语法: loop_detect_status code;

默认值: loop_detect_status 508;

上下文: http, server, location

设置当请求超过允许的循环限制时返回的 HTTP 状态码。该代码必须在 400599 之间(客户端或服务器错误)。

loop_detect_max_allow_loops

语法: loop_detect_max_allow_loops number;

默认值: loop_detect_max_allow_loops 10;

上下文: http, server, location

设置在阻止请求之前允许的最大循环次数。该数字必须大于 0。

变量

$loop_detect_current_loops

返回从 CDN-Loop 头中提取的当前检测到的循环计数。此值表示您的请求已经通过的 CDN 节点的跳数。

$loop_detect_proxy_add_cdn_loop

构造要发送到下游代理的新 CDN-Loop 头值。此值包括:

  1. 当前 CDN 节点的标识符和递增的循环计数(例如,my_cdn; loops=2)。
  2. 原始 CDN-Loop 头中的其他剩余条目(如果有)。

示例用法:

location / {
    proxy_set_header CDN-Loop $loop_detect_proxy_add_cdn_loop;
    proxy_pass http://backend;
}

工作原理

  1. 检测: 模块解析 CDN-Loop 头以识别跳数。每个跳数的格式为: 格式:Cdn-Loop: <cdn_id>; loops=<count>, ... 示例:Cdn-Loop: my_cdn; loops=2, another_cdn; loops=1

  2. 跟踪: 从头中提取当前跳数(current_loops)。 模块递增计数并为下游代理构造新的 CDN-Loop 值。

  3. 阻止: 如果检测到的循环计数超过 loop_detect_max_allow_loops,NGINX 将返回配置的 loop_detect_status(例如,508)。

GitHub

您可以在 nginx-module-loop-detect 的 GitHub 仓库 中找到有关此模块的其他配置提示和文档。