/etc/nginx/conf.d/default.conf
1.Define a limit_req_zone
# 定義限流區塊
limit_req_zone $binary_remote_addr zone=limit_zone:10m rate=2r/s;
limit_req_zone $binary_remote_addr zone=limit_zone:10m rate=2r/s;是一个 Nginx 配置指令,用于定义请求限制区域和速率限制。
limit_req_zone $binary_remote_addr zone=limit_zone:10m:表示根据客户端的二进制 IP 地址创建一个名为limit_zone的限制区域,大小为 10MB。这个限制区域用于存储限制相关的信息,比如请求计数器、时间戳等。
rate=2r/s:表示该限制区域内的速率限制为每秒处理最多 2 个请求。这意味着,当超过这个速率时,Nginx 会延迟处理或拒绝多余的请求。这个配置指令将为每个客户端 IP 地址创建一个限制区域,并将其与请求速率设置关联。当 Nginx 收到请求时,会根据客户端的 IP 地址和限制区域来判断请求是否超过了设置的速率限制。
2.Set real IP
# 設定接收真實 IP 的標頭
    real_ip_header X-Forwarded-For;
    set_real_ip_from 0.0.0.0/0;3.Set limit_req
location /api {
        # 設定限制IP請求數的參數
        limit_req zone=limit_zone burst=5;
        
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }4.default.conf complete code
#changed by Rubin
# 定義限流區塊
limit_req_zone $binary_remote_addr zone=limit_zone:10m rate=2r/s;
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
    #access_log  /var/log/nginx/host.access.log  main;
    
    # 設定接收真實 IP 的標頭
    real_ip_header X-Forwarded-For;
    set_real_ip_from 0.0.0.0/0;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    
    location /api {
        # 設定限制IP請求數的參數
        limit_req zone=limit_zone burst=5;
        
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
/etc/nginx/nginx.conf
1.re-define log_format
log_format main '$server_name $remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    '$ssl_protocol $ssl_cipher $upstream_addr $request_time $upstream_response_time';2.Test limit

3.nginx log

Demo source code: https://download.csdn.net/download/wish366/89346309?spm=1001.2101.3001.9500



















