nginx訪問控制-限速

nginx訪問控制-限速

可以通過ngx_http_limit_conn_module和ngx_http_limit_req_module模塊來實現限速的功能。

ngx_http_limit_conn_module

該模塊主要限制下載速度。

  1. 併發限制
    配置示例
http
{
    ...
    limit_conn_zone $binary_remote_addr zone=test:10m;
    ...
    server
    {
        ...
        limit_conn test10;
        ...   
    }
}

說明:首先用limit_conn_zone定義了一個內存區塊索引test,大小爲10m,它以$binary_remote_addr作爲key。
該配置只能在http裏面配置,不支持在server裏配置。

limit_conn 定義針對test這個zone,併發連接爲10個。在這需要注意一下,這個10指的是單個IP的併發最多爲10個。
  1. 速度限制
location ~ /download/ {
    ...
    limit_rate_after 512k;
    limit_rate 150k;
    ...
}

說明:limit_rate_after定義當一個文件下載到指定大小(本例中爲512k)之後開始限速;
limit_rate 定義下載速度爲150k/s。

注意:這兩個參數針對每個請求限速。

ngx_http_limit_req_module

該模塊主要用來限制請求數。

  1. limit_req_zone
語法: limit_req_zone $variable zone=name:size rate=rate;
默認值: none
配置段: http

設置一塊共享內存限制域用來保存鍵值的狀態參數。 特別是保存了當前超出請求的數量。 
鍵的值就是指定的變量(空值不會被計算)。
如limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

說明:區域名稱爲one,大小爲10m,平均處理的請求頻率不能超過每秒一次,鍵值是客戶端IP。
使用$binary_remote_addr變量, 可以將每條狀態記錄的大小減少到64個字節,這樣1M的內存可以保存大約1萬6千個64字節的記錄。
如果限制域的存儲空間耗盡了,對於後續所有請求,服務器都會返回 503 (Service Temporarily Unavailable)錯誤。
速度可以設置爲每秒處理請求數和每分鐘處理請求數,其值必須是整數,
所以如果你需要指定每秒處理少於1個的請求,2秒處理一個請求,可以使用 “30r/m”。
  1. limit_req
語法: limit_req zone=name [burst=number] [nodelay];
默認值: —
配置段: http, server, location

設置對應的共享內存限制域和允許被處理的最大請求數閾值。 
如果請求的頻率超過了限制域配置的值,請求處理會被延遲,所以所有的請求都是以定義的頻率被處理的。 
超過頻率限制的請求會被延遲,直到被延遲的請求數超過了定義的閾值,
這時,這個請求會被終止,並返回503 (Service Temporarily Unavailable) 錯誤。

這個閾值的默認值爲0。如:
limit_req_zone $binary_remote_addr zone=test:10m rate=1r/s;
server {
    location /upload/ {
        limit_req zone=testburst=5;
    }
}

限制平均每秒不超過一個請求,同時允許超過頻率限制的請求數不多於5個。

如果不希望超過的請求被延遲,可以用nodelay參數,如:

limit_req zone=testburst=5 nodelay;

示例

http {
    limit_req_zone $binary_remote_addr zone=test:10m rate=1r/s;

    server {
        location  ^~ /download/ {  
            limit_req zone=testburst=5;
        }
    }
}

設定白名單IP

如果是針對公司內部IP或者lo(127.0.0.1)不進行限速,如何做呢?這就要用到geo模塊了。

假如,預把127.0.0.1和192.168.100.0/24網段設置爲白名單,需要這樣做。
在http { }裏面增加:
geo $limited {
    default 1;
    127.0.0.1/32 0;
    192.168.100.0/24 0;
}

map $limited $limit {
	1 $binary_remote_addr;
    0 "";
}

原來的 “limit_req_zone $binary_remote_addr ” 改爲“limit_req_zone $limit”

完整示例:

http {
	geo $limited {
		default 1;
		127.0.0.1/32 0;
		192.168.100.0/24 0;
	}

	map $limited $limit {
		1 $binary_remote_addr;
		0 "";
	}
    
    limit_req_zone $limit zone=test:10m rate=1r/s;

    server {
        location  ^~ /download/ {  
            limit_req zone=testburst=5;
        }
    }
}

實驗:分別添加配置文件

[root@centos-03 vhost]# vim ../nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    limit_conn_zone $binary_remote_addr zone=test:10m;
    limit_conn_status 503;
    limit_conn_log_level error;
    log_format  main  '$remote_addr
[root@centos-03 vhost]# vim 1.conf
[root@centos-03 vhost]# cat 1.conf
server {
        listen 80;
        server_name www.1.com;
        index index.html;
        root /data/wwwroot/www.1.com;
        access_log /tmp/1.log;
        location /
        {
                limit_conn test2;
        }
}


[root@centos-03 vhost]# yum install -y httpd (安裝apache支持ab命令)

[root@centos-03 vhost]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

127.0.0.1 www.1.com (添加host)

壓測

[root@centos-03 vhost]# ab -n 5 -c 5 http://www.1.com/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking www.1.com (be patient).....done
 
 
Server Software:        nginx/1.14.0
Server Hostname:        www.1.com
Server Port:            80
 
Document Path:          /
Document Length:        10 bytes
 
Concurrency Level:      5
Time taken for tests:   0.002 seconds
Complete requests:      5
Failed requests:        0
Write errors:           0
Total transferred:      1200 bytes
HTML transferred:       50 bytes
Requests per second:    2403.85 [#/sec] (mean)
Time per request:       2.080 [ms] (mean)
Time per request:       0.416 [ms] (mean, across all concurrent requests)
Transfer rate:          563.40 [Kbytes/sec] received
 
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       0
Processing:     1    1   0.1      1       1
Waiting:        1    1   0.0      1       1
Total:          1    1   0.1      1       1
 
Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      1
  98%      1
  99%      1
 100%      1 (longest request)

[root@centos-03 vhost]#

[root@centos-03 vhost]# cat /tmp/1.log (效果不明顯文件太小了無壓力)
127.0.0.1 - - [28/Jul/2018:07:20:24 +0800] "GET / HTTP/1.0" 200 10 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:20:24 +0800] "GET / HTTP/1.0" 200 10 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:20:24 +0800] "GET / HTTP/1.0" 200 10 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:20:24 +0800] "GET / HTTP/1.0" 200 10 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:20:24 +0800] "GET / HTTP/1.0" 200 10 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:52:39 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:52:39 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:52:39 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:07:52:39 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"

nginx訪問控制-限速2

1.限制速度添加配置選項

[root@centos-03 vhost]# vim 1.conf ^C
[root@centos-03 vhost]# cat 1.conf
server {
        listen 80;
        server_name www.1.com;
        index index.html;
        root /data/wwwroot/www.1.com;
        access_log /tmp/1.log;
        location /
        {
                #limit_conn aming 2;
                limit_rate 10k;
        }
}
[root@centos-03 vhost]#

[root@centos-03 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@centos-03 vhost]#
2.瀏覽器測試下載速度,在本地添加host配置





3.下載速度變成每秒10k左右



4.改爲限制爲1000試試


access_log /tmp/1.log;
location /
{
        #limit_conn aming 2;
        limit_rate 1000k;
}
 


[root@centos-03 vhost]# /usr/local/nginx/sbin/nginx -t      
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@centos-03 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@centos-03 vhost]#
  



nginx訪問控制-限速3
1.添加配置文件


[root@centos-03 vhost]# vim ../nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    limit_conn_zone $binary_remote_addr zone=aming:10m;
    limit_conn_status 503;
    limit_conn_log_level error;
    limit_req_zone $binary_remote_addr zone=aming1:10m rate=2r/s;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $host $server_port';
2.配置虛擬主機配置文件


[root@centos-03 vhost]# vim 1.conf
server {
        listen 80;
        server_name www.1.com;
        index index.html;
        root /data/wwwroot/www.1.com;
        access_log /tmp/1.log;
        #location /
        #{
                #limit_conn aming 2;
                #limit_rate 1000k;
        #}
        limit_req zone=aming1 burst=5;       
}
3.ab請求測試


[root@centos-03 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@centos-03 vhost]# ab -n 10 -c 10 http://www.1.com/filebeat-6.3.1-x86_64.rpm
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking www.1.com (be patient).....done
 
 
Server Software:        nginx/1.14.0
Server Hostname:        www.1.com
Server Port:            80
 
Document Path:          /filebeat-6.3.1-x86_64.rpm
Document Length:        213 bytes
 
Concurrency Level:      10
Time taken for tests:   2.509 seconds
Complete requests:      10
Failed requests:        6
   (Connect: 0, Receive: 0, Length: 6, Exceptions: 0)
Write errors:           0
Non-2xx responses:      4
Total transferred:      76799974 bytes
HTML transferred:       76797678 bytes
Requests per second:    3.98 [#/sec] (mean)
Time per request:       2509.443 [ms] (mean)
Time per request:       250.944 [ms] (mean, across all concurrent requests)
Transfer rate:          29887.10 [Kbytes/sec] received
 
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       0
Processing:     2  756 952.9    507    2508
Waiting:        1  752 950.0    501    2502
Total:          2  756 952.9    507    2508
 
Percentage of the requests served within a certain time (ms)
  50%    507
  66%   1008
  75%   1508
  80%   2012
  90%   2508
  95%   2508
  98%   2508
  99%   2508
 100%   2508 (longest request)
[root@centos-03 vhost]#
4.查看日誌


[root@centos-03 vhost]# tail -n 10 /tmp/1.log
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 503 213 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:20 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:21 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:21 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:22 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
127.0.0.1 - - [28/Jul/2018:08:28:22 +0800] "GET /filebeat-6.3.1-x86_64.rpm HTTP/1.0" 200 12799471 "-" "ApacheBench/2.3"
[root@centos-03 vhost]#
5.添加nodelay(這樣限速就不受影響了)


[root@centos-03 vhost]# vim 1.conf

server {
        listen 80;
        server_name www.1.com;
        index index.html;
        root /data/wwwroot/www.1.com;
        access_log /tmp/1.log;
        #location /
        #{
                #limit_conn aming 2;
                #limit_rate 1000k;
        #}
        limit_req zone=aming1 burst=5 nodelay;
}
6.ab測試瞬間完成(生產環境中不建議加nodelay)

[root@centos-03 vhost]# !ab
ab -n 10 -c 10 http://www.1.com/filebeat-6.3.1-x86_64.rpm
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
 
Benchmarking www.1.com (be patient).....done
 
 
Server Software:        nginx/1.14.0
Server Hostname:        www.1.com
Server Port:            80
 
Document Path:          /filebeat-6.3.1-x86_64.rpm
Document Length:        213 bytes
 
Concurrency Level:      10
Time taken for tests:   0.021 seconds
Complete requests:      10
Failed requests:        6
   (Connect: 0, Receive: 0, Length: 6, Exceptions: 0)
Write errors:           0
Non-2xx responses:      4
Total transferred:      76799974 bytes
HTML transferred:       76797678 bytes
Requests per second:    469.04 [#/sec] (mean)
Time per request:       21.320 [ms] (mean)
Time per request:       2.132 [ms] (mean, across all concurrent requests)
Transfer rate:          3517822.45 [Kbytes/sec] received
 
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       0
Processing:     4   14   7.9     20      20
Waiting:        1    4   1.2      4       4
Total:          5   14   7.9     20      20
 
Percentage of the requests served within a certain time (ms)
  50%     20
  66%     20
  75%     20
  80%     20
  90%     20
  95%     20
  98%     20
  99%     20
 100%     20 (longest request)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章