ubuntu

Ubuntu PHP-FPM如何限制请求速率

小樊
34
2025-06-15 08:45:00
栏目: 编程语言

在Ubuntu上使用PHP-FPM时,可以通过配置Nginx或Apache来限制请求速率。这里分别介绍如何在这两种Web服务器上实现请求速率限制。

使用Nginx限制请求速率

  1. 安装Nginx(如果尚未安装):
sudo apt update
sudo apt install nginx
  1. 打开Nginx配置文件:
sudo nano /etc/nginx/nginx.conf
  1. http块中添加以下内容:
http {
    # ...
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
    # ...
}

这里,我们创建了一个名为mylimit的存储区域,用于存储IP地址和请求计数。rate=1r/s表示每秒允许的最大请求数为1。

  1. server块中添加以下内容:
server {
    # ...
    location / {
        # ...
        limit_req zone=mylimit burst=5 nodelay;
        # ...
    }
}

这里,我们使用limit_req指令应用限制。burst=5表示允许短时间内的突发请求达到5个,nodelay表示不对请求进行延迟处理。

  1. 保存并退出配置文件,然后重启Nginx:
sudo nginx -t
sudo systemctl restart nginx

使用Apache限制请求速率

  1. 安装Apache(如果尚未安装):
sudo apt update
sudo apt install apache2
  1. 启用mod_ratelimit模块:
sudo a2enmod ratelimit
  1. 打开Apache配置文件:
sudo nano /etc/apache2/apache2.conf
  1. <IfModule mod_ratelimit.c>块中添加以下内容:
<IfModule mod_ratelimit.c>
    <Location />
        SetOutputFilter RATE_LIMIT
        SetEnv rate-limit 1
        SetEnv rate-initial-burst 5
    </Location>
</IfModule>

这里,我们设置了每秒允许的最大请求数为1,以及短时间内的突发请求达到5个。

  1. 保存并退出配置文件,然后重启Apache:
sudo systemctl restart apache2

现在,您已经在Ubuntu上使用PHP-FPM配置了请求速率限制。请注意,这些示例仅适用于单个IP地址的请求速率限制。如果您需要基于用户、API密钥或其他条件的限制,可能需要使用其他模块或自定义解决方案。

0
看了该问题的人还看了