Nginx配置限流 使用Nginx自有模块, 配置实现限流操作
limit_req
漏桶算法, 先进先出
Nginx模块: ngx_http_limit_req_module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 http { keepalive_timeout 75s ; sendfile on ; tcp_nopush on ; geo $limit { default 1 ; 10.0.0.0/8 0; 192.168.0.0/24 0; } map $limit $limit_key { 0 ""; 1 $binary_remote_addr; } limit_req_zone $binary_remote_addr zone=ratelimit:30m rate=15r/s; server { listen 80 ; server_name my.domain.cn; charset utf-8 ; root /opt/web/order/dist; location / { limit_req zone=ratelimit burst=5 nodelay; limit_req_log_level error ; limit_req_status 503 ; index /index.html; try_files $uri $uri/ /index.html; } } }
白名单 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 geo $limit { default 1 ; 10.0.0.0/8 0; 192.168.0.0/24 0; } map $limit $limit_key { 0 ""; 1 $binary_remote_addr; } limit_req_zone $limit_key zone=mylimit:10m rate=2r/s;limit_req_zone $binary_remote_addr zone=myLimit2:10m rate=10r/s;server { location ~* \.(html)$ { limit_req zone=mylimit burst=5 nodelay; limit_req zone=myLimit2 burst=5 nodelay; } }
实例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 limit_req_zone $binary_remote_addr zone=ratelimit:30m rate=5r/s;server { listen 9728 ; server_name 192.168.1.251 ; root /home/norman/adx/flow_receive; index index.php; try_files $uri $uri/ @rewrite; location @rewrite { if ($request_filename ~* "\.(js|ico|gif|jpe?g|bmp|png|css)$") { break; } rewrite ^/(.*)$ /index.php?_url=/$1 ; } location ~ \.php$ { limit_req zone=ratelimit burst=5 nodelay; limit_conn_status 503 ; root /home/norman/adx/flow_receive; fastcgi_pass 127.0.0.1:9000 ; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
limit_conn
根据特定的key来限制连接的数量,需要注意的是并不是所有的连接都会被算入其中,只有当一个连接的整个请求头被读取并且已经被nginx服务器处理的时候才会算入限制中。
1 2 3 4 5 6 7 8 9 10 11 limit_conn_zone $binanry_remote_addr zone=conn_zone:1m server{ location / { limit_conn conn_zone 1 ; } }
limit_rate
限制用户和服务器之间传输的字节数,最常用的场景可能就是下载/上传限速。
1 2 3 4 5 6 7 8 9 10 11 12 13 location /flv/ { flv; limit_rate_after 500k ; limit_rate 50k ; }