鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # 限制请求
  2. ### limit_conn_zone限速配置
  3. ```
  4. http {
  5. limit_conn_zone $binary_remote_addr zone=one:10m; //为每个IP定义一个存储session的容器,一个session有32bytes, 这里10兆的容器,(10*1024*1024)/32=320000个session
  6. server {
  7. listen 80;
  8. server_name www.abc.com;
  9. location / {
  10. limit_conn one 1; //one对应上面的one, 1限制每个IP只能发起一个并发连接
  11. limit_rate 300k;//对连接的限速,而不是对IP限速。如果一个IP允许两个并发连接,那么针对这个IP的限速limit_rate*2
  12. }
  13. }
  14. }
  15. ```
  16. ### limit_req_zone限制访问频率
  17. ```
  18. http {
  19. limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
  20. server {
  21. location / {
  22. limit_req zone=one bust=10;//每个ip一秒钟只处理一个请求,这样会导致其它队列等待,占用tcp连接。如果limit_req zone=one bust=10 nodelay; 就可以把多余的请求丢掉,不会占用tcp连接
  23. }
  24. }
  25. }
  26. ```
  27. ### 实际应用
  28. 在实际应用中,不能对所有资源限制,比如图片什么的不能限制,所以需要把图片等排除出来。
  29. ```
  30. http {
  31. limit_conn_zone $binary_remote_addr zone=addr:10m;
  32. limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
  33. server {
  34. location ~ .*\.(gif|png|css|js|icon)$ {
  35. proxy_set_header Host $http_host;
  36. proxy_set_hreader X-Real_IP $romote_addr;
  37. proxy_set_hreader X-Forwarded-For $proxy_add_x_forwarded_for;
  38. }
  39. location ~* .*\.(jpeg|jpg|JPG)$ {
  40. proxy_set_header Host $http_host;
  41. proxy_set_header X-Real_IP $remote_addr;
  42. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  43. }
  44. location / {
  45. proxy_set_header Host $http_host;
  46. proxy_set_header X-Real_IP $remote_addr;
  47. proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
  48. limit_conn addr 3;
  49. limit_req zone=one bust=5;
  50. }
  51. }
  52. }
  53. ```