在nginx中實現單位時間內限制訪問頻率的教程_nginx

來源:互聯網
上載者:User

首先說一下遇到這個問題是因為網站被攻擊,阿里雲警示,想到要限制一下訪問頻率,而不是限制ip(限制ip的方案稍後給出)。nginx串連資源被吃空返回狀態代碼是502,添加本方案限制後返回599,與正常狀態代碼區別開。
步驟如下:

首先nginx.conf裡面添加如下內容:

map $http_x_forwarded_for  $clientRealIp {    "" $remote_addr;    ~^(?P<firstAddr>[0-9\.]+),?.*$  $firstAddr;    }    ###safe setting to limit the request number per second    limit_req_status 599;    limit_req_zone $clientRealIp zone=allips:70m rate=5r/s;

session池大小70M,如果限制的ip很多 那可以調小,如果限制的ip很少,那可訪問的ip很多則要調大
每秒5個請求,這個也是根據情況調節的,5個是比較合適或者說偏大一點點的。

然後修改www.xxoo.com.conf(這是lnmp針對每個虛擬機器主機都有個設定檔)server裡面,location上面添加如下一行:

limit_req zone=allips burst=5 nodelay;

這樣重啟nginx就可以寫個指令碼測測並發了。

如下提供一個python並髮腳本:

import threadingimport time,urllib2url = 'http://sf.gg/'def worker():  try:   response = urllib2.urlopen(url)   print response.getcode()  except urllib2.HTTPError, e:   print e.codefor i in range(2000):  t = threading.Thread(target=worker)  t.start()

其中2000和http://sf.gg/都是可以修改的,然後執行 python *.py > out 就可以分析out檔案裡面的狀態代碼的分布了,如果599特別多說頻率限制起到作用了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.