跳转至

redis-rate-limit: 基于 Redis 的 Nginx 限流模块

安装

您可以在任何基于 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-redis-rate-limit
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-redis-rate-limit

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

load_module modules/ngx_http_rate_limit_module.so;

本文档描述了 nginx-module-redis-rate-limit v1.0.0,发布于 2022 年 7 月 16 日。


CI status

这是一个基于 Redis 的 Nginx Web 服务器限流模块。

此实现基于以下 Redis 模块

它提供了一个相对复杂的 通用单元速率算法 的简单实现,仅用 130 行 C 代码,无需外部依赖。

概述

upstream redis {
   server 127.0.0.1:6379;

   # 或者: server unix:/var/run/redis/redis.sock;

   # 最多 1024 个连接的池
   keepalive 1024;
}

geo $limit {
    default 1;
    10.0.0.0/8 0;
    192.168.0.0/24 0;
}

map $limit $limit_key {
    0 "";
    1 $remote_addr;
}

rate_limit_status 429;

location = /limit {
    rate_limit $limit_key requests=15 period=1m burst=20;
    rate_limit_pass redis;
}

location = /limit_b {
    rate_limit $limit_key requests=20 period=1m burst=25;
    rate_limit_prefix b;
    rate_limit_pass redis;
}

location = /quota {
    rate_limit $limit_key requests=15 period=1m burst=20;
    rate_limit_quantity 0;
    rate_limit_pass redis;
    rate_limit_headers on;
}

在这里我们假设您会将 Nginx 安装在 /opt/nginx/ 下。

./configure --prefix=/opt/nginx \ --add-module=rate-limit-nginx-module/

make -j$(nproc) make install

## 测试套件

运行测试套件需要以下依赖项:

* Nginx 版本 >= 1.9.11

* Perl 模块:
    * [Test::Nginx](https://metacpan.org/pod/Test::Nginx::Socket)

* Nginx 模块:
    * ngx_http_rate_limit_module(即此模块)

* Redis 模块:
    * [redis-rate-limiter](https://github.com/onsigntv/redis-rate-limiter)

* 应用程序:
    * redis:监听默认端口 6379。

要在默认测试模式下运行整个测试套件:
```bash
cd /path/to/rate-limit-nginx-module
export PATH=/path/to/your/nginx/sbin:$PATH
prove -I/path/to/test-nginx/lib -r t

要运行特定的测试文件:

cd /path/to/rate-limit-nginx-module
export PATH=/path/to/your/nginx/sbin:$PATH
prove -I/path/to/test-nginx/lib t/sanity.t

要在特定测试文件中运行特定测试块,请在要运行的测试块中添加行 --- ONLY,然后使用 prove 工具运行该 .t 文件。

GitHub

您可以在 nginx-module-redis-rate-limit 的 GitHub 仓库 中找到此模块的其他配置提示和文档。