nginx限制ip连接数和带宽

今天有个人问我,nginx怎么限制ip连接数,突然想不起来了,年龄大了,脑子不怎么好使了。还要看一下配置才想起了。那个人又问我,你测试过的吗?一下子把我问蒙了,我真没测试过了,也不知道启作用了没有。下面我做了一下测试。以前用apache的时候到是做过测试,apache怎么限制ip数,请参考:利用apache限制IP并发数和下载流量控制

1,配置nginx.conf

  1. http{  
  2. .............  
  3. limit_zone   one  $binary_remote_addr  10m;  //我记得默认配置就有,只不过是注释掉了,如果没有加一下  
  4. ..............  
  5.  server{  
  6.  .................  
  7.  location {  
  8.  .........  
  9.  limit_conn one 20;          //连接数限制  
  10.  limit_rate 500k;            //带宽限制  
  11.  ........  
  12.  }  
  13.  .................  
  14.  }  
  15. .............  
  16. }  
  17.   
  18. [root@localhost nginx]# /etc/init.d/nginx reload //重新加载  

2,测试限制ip连接数

  1. [root@localhost nginx]#  webbench -c 100 -t 2 http://127.0.0.1/index.php  
  2. Webbench - Simple Web Benchmark 1.5  
  3. Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.  
  4.   
  5. Benchmarking: GET http://127.0.0.1/index.php  
  6. 100 clients, running 2 sec.  
  7.   
  8. Speed=429959 pages/min, 2758544 bytes/sec.  
  9. Requests: 14332 susceed, 0 failed.  
  10.   
  11. [root@localhost nginx]# cat /var/log/nginx/access.log|grep 503 |more   //这样的数据有很多,最好加个more或者less  
  12. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  13. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  14. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  15. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  16. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  17. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  18. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  19. 127.0.0.1 - - [25/Apr/2012:17:52:21 +0800] "GET /index.php HTTP/1.0" 503 213 "-" "WebBench 1.5" -  
  20. ..............................................................................................  

通过以上测试,可以得出限制ip连接数是没有问题的,但是限制带宽看不出来,说实话这个不好测试,所以就没测试了。

原文地址:https://www.cnblogs.com/canphp/p/4763501.html