因業務需求常常會有搶購業務,所以須要在負載均衡前端進行限流錯誤。本文一樣也適用於防止CC.html
limit_req_zone $server_name zone=sname:10m rate=1r/s; #限制服務器每秒只能有一次訪問成功 #limit_req_zone $binary_remote_addr zone=one:3m rate=1r/s; #限制IP,每秒只能訪問一次 #limit_req_zone $binary_remote_addr$uri zone=two:3m rate=1r/s; #限制IP和路徑不帶參數, #limit_req_zone $binary_remote_addr$request_uri zone=thre:3m rate=1r/s; #限制IP和帶參數的路徑 server { listen 80; server_name www.abc.com; location / { include host/proxy.cnf; proxy_pass http://backend; } location /api/createOrder { limit_req zone=sname; #不帶突發,只能有一次正常請求 limit_req_status 503; #設置返回的狀態碼是503 #limit_req zone=sname burst=5 nodelay; #最大併發是5,而且實時處理 include host/proxy.cnf; proxy_pass http://backend; error_page 503 =200 /50x.html; #這裏很重要,能夠將錯誤的狀態碼503,返回結果的時候是200 } location = /50x.html { if ($http_user_agent ~* "mobile|android|iPhone|iphone|ios|iOS"){ #default_type application/json; return 200 '{"msg": "活動過於火爆,請稍後重試!","data": {},"code": -1}'; #設置移動端返回錯誤的信息顯示 } root html; #若是是PC端返回一個HTML頁面 } }
重點: 正常狀況下,若是設置了限流,返回是503的狀態碼,這對於移動端來講即使是你返回JSON數據可是客戶端時不認的,這個時候巧妙的經過 error_page 403 =200 /50x.html;將狀態碼設置爲200前端
以上只是使用了ngx_limit_req_module,同時也能夠使用ngx_limit_conn_module模塊。node
以上參考:https://gist.github.com/simlegate/75b18359316cc33d8e20android
特別是一些諮詢類網站若是備爬蟲盯上,服務器可能會被爬蟲給乾死(小網站就是這樣)
那麼怎麼辦呢,咱們能夠使用變量去作ios
#全局配置 limit_req_zone $spider zone=spider:60m rate=200r/m; #限制爬蟲每分鐘只能跑200次 #某個server中 limit_req zone=spider burst=5 nodelay; if ($http_user_agent ~* 「spider|bot」) { set $spider $http_user_agent; #設置變量,進入這裏的就進行限速 }