ngx_http_limit_conn_module 这个模块是用于限制每个定义的key只的连接数,特别是单ip的链接数
用于定义key设置的最大连接数量,当超过设定的最大连接数时,服务器会返回错误代码。
nginx的配置如下:
修改nignx配置文件:
在http字段中添加:limit_conn_zone $binary_remote_addr zone=addr:10m;
在server字段location中添加:limit_conn addr 1; <<限制单ip的并发连接数为1
语法:limit_conn_zone key zone=name:size;
key 呢可以是字符串,nginx自带的变量$binary_remote_addr 和$server_name
语法:limit_conn zone number;
zone为上文中配置的zone区域,以及并发连接数
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 8990;
server_name www.ofo.com;
root /home/inca/www;
location / {
index index.html index.php index.htm;
limit_conn addr 1;
}
使用ab命令进行测试:
#ab -c 5 -n 1000 http://192.168.1.251:8990/
查看服务端访问日志:
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 200 5 "-" "ApacheBench/2.3"
192.168.1.23 - - [14/Apr/2018:17:20:59 +0800] "GET / HTTP/1.0" 503 212 "-" "ApacheBench/2.3"
可以看出来状态码202和503都是1:1的出现。Nginx已经做出访问的限制。
限制虚拟主机连接数:
不仅可以限制单ip的并发连接数。还可以限制虚拟主机的总连接数量,甚至可以对两者同时限制。
http字段上文信息 ;
limit_conn_zone $server_name zone=perserver:10m;
server字段下文信息:
limit_conn perserver 2;·