Nginx如何封禁IP和IP段的實現(xiàn)
寫在前面
Nginx不僅僅只是一款反向代理和負載均衡服務(wù)器,它還能提供很多強大的功能,例如:限流、緩存、黑白名單和灰度發(fā)布等等。在之前的文章中,我們已經(jīng)介紹了Nginx提供的這些功能。小伙伴們可以到【Nginx專題】進行查閱。今天,我們來介紹Nginx另一個強大的功能:禁用IP和IP段。
禁用IP和IP段
Nginx的ngx_http_access_module 模塊可以封配置內(nèi)的ip或者ip段,語法如下:
deny IP; deny subnet; allow IP; allow subnet; # block all ips deny all; # allow all ips allow all;
如果規(guī)則之間有沖突,會以最前面匹配的規(guī)則為準。
配置禁用ip和ip段
下面說明假定nginx的目錄在/usr/local/nginx/。
首先要建一個封ip的配置文件blockips.conf,然后vi blockips.conf編輯此文件,在文件中輸入要封的ip。
deny 1.2.3.4; deny 91.212.45.0/24; deny 91.212.65.0/24;
然后保存此文件,并且打開nginx.conf文件,在http配置節(jié)內(nèi)添加下面一行配置:
include blockips.conf;
保存nginx.conf文件,然后測試現(xiàn)在的nginx配置文件是否是合法的:
/usr/local/nginx/sbin/nginx -t
如果配置沒有問題,就會輸出:
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
如果配置有問題就需要檢查下哪兒有語法問題,如果沒有問題,需要執(zhí)行下面命令,讓nginx重新載入配置文件。
/usr/local/nginx/sbin/nginx -s reload
僅允許內(nèi)網(wǎng)ip
如何禁止所有外網(wǎng)ip,僅允許內(nèi)網(wǎng)ip呢?
如下配置文件
location / { # block one workstation deny 192.168.1.1; # allow anyone in 192.168.1.0/24 allow 192.168.1.0/24; # drop rest of the world deny all; }
上面配置中禁止了192.168.1.1,允許其他內(nèi)網(wǎng)網(wǎng)段,然后deny all禁止其他所有ip。
格式化nginx的403頁面
如何格式化nginx的403頁面呢?
首先執(zhí)行下面的命令:
cd /usr/local/nginx/html vi error403.html
然后輸入403的文件內(nèi)容,例如:
<html> <head><title>Error 403 - IP Address Blocked</title></head> <body> Your IP Address is blocked. If you this an error, please contact binghe with your IP at test@binghe.com </body> </html>
如果啟用了SSI,可以在403中顯示被封的客戶端ip,如下:
Your IP Address is <!--#echo var="REMOTE_ADDR" --> blocked.
保存error403文件,然后打開nginx的配置文件vi nginx.conf,在server配置節(jié)內(nèi)添加下面內(nèi)容。
# redirect server error pages to the static page error_page 403 /error403.html; location = /error403.html { root html; }
然后保存配置文件,通過nginx -t命令測試配置文件是否正確,若正確通過nginx -s reload載入配置。
到此這篇關(guān)于Nginx如何封禁IP和IP段的實現(xiàn)的文章就介紹到這了,更多相關(guān)Nginx 封禁IP和IP段內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。