Nginx panic current limit configuration to implement parsing

  • 2020-05-17 07:49:15
  • OfStack

Because the business demand often has the rush business, therefore needs in the load balancing front end carries on the current limiting error. This article also applies to preventing CC.


  limit_req_zone $server_name zone=sname:10m rate=1r/s;        # Limit the server to one per second 1 The second visit was successful 
    #limit_req_zone $binary_remote_addr zone=one:3m rate=1r/s;    # limit IP , only accessible per second 1 time 
    #limit_req_zone $binary_remote_addr $uri zone=two:3m rate=1r/s;  # limit IP And path without parameters, 
    #limit_req_zone $binary_remote_addr $request_uri zone=thre:3m rate=1r/s;  # limit IP And a parameterized path  

  server {
    listen    80;
    server_name www.abc.com;
    location / {
        include host/proxy.cnf;
        proxy_pass http://backend;
    }
    location /api/createOrder {
        limit_req zone=sname;  # No sudden, can only have 1 Subnormal request 
        limit_req_status 503;    # The status code returned by setting is 503
        #limit_req zone=sname burst=5 nodelay;  # The maximum concurrency is 5 And do it in real time 
        include host/proxy.cnf;
        proxy_pass http://backend;
        error_page 503 =200 /50x.html;   # It is important here to put the wrong status code 503 , when you return the result 200
    }
    location = /50x.html {
        if ($http_user_agent ~* "mobile|android|iPhone|iphone|ios|iOS"){
            #default_type application/json;
            return 200 '{"msg": " The activity is too hot, please try again later !","data": {},"code": -1}';  # Set the mobile terminal to return an error message 
        }
        root  html;   # If it is PC The return 1 a HTML page 
    }
    }

Key points: under normal circumstances, if the current limit is set, the status code returned is 503, which is not recognized by the client on the mobile terminal even if you return the JSON data. In this case, error_page 403 = 200/50x.html; Set the status code to 200

The ngx_limit_req_module module is only used above, and the ngx_limit_conn_module module can also be used.

The above reference: https: / / gist github. b18359316cc33d8e20 com simlegate / 75

In particular, some consulting websites if prepared to target a crawler, the server may be dried up by the crawler (small websites are like this)
So what do we do? We can use variables to do that


# Global configuration 
limit_req_zone $spider zone=spider:60m rate=200r/m;  # Limit crawlers to running per minute 200 time 
# a server In the 
limit_req zone=spider burst=5 nodelay;
if ($http_user_agent ~*  " spider|bot " ) {
  set $spider $http_user_agent;   # You set the variable, you go in here and you limit the speed 
}

Related articles: