在Ubuntu上使用PHP-FPM时,可以通过配置Nginx或Apache来限制请求速率。这里分别介绍如何在这两种Web服务器上实现请求速率限制。
使用Nginx限制请求速率
sudo apt update
sudo apt install nginx
sudo nano /etc/nginx/nginx.conf
http块中添加以下内容:http {
    # ...
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
    # ...
}
这里,我们创建了一个名为mylimit的存储区域,用于存储IP地址和请求计数。rate=1r/s表示每秒允许的最大请求数为1。
server块中添加以下内容:server {
    # ...
    location / {
        # ...
        limit_req zone=mylimit burst=5 nodelay;
        # ...
    }
}
这里,我们使用limit_req指令应用限制。burst=5表示允许短时间内的突发请求达到5个,nodelay表示不对请求进行延迟处理。
sudo nginx -t
sudo systemctl restart nginx
使用Apache限制请求速率
sudo apt update
sudo apt install apache2
mod_ratelimit模块:sudo a2enmod ratelimit
sudo nano /etc/apache2/apache2.conf
<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个。
sudo systemctl restart apache2
现在,您已经在Ubuntu上使用PHP-FPM配置了请求速率限制。请注意,这些示例仅适用于单个IP地址的请求速率限制。如果您需要基于用户、API密钥或其他条件的限制,可能需要使用其他模块或自定义解决方案。