1寫在前面
Nginx不僅僅只是一款反向代理和負載均衡服務器,它還能提供很多強大的功能,例如:限流、緩存、黑白名單和灰度發布等等。在之前的文章中,我們已經介紹了Nginx提供的這些功能。今天,我們來介紹Nginx另一個強大的功能:禁用IP和IP段。
2禁用IP和IP段
Nginx的ngx_http_access_module 模塊可以封配置內的ip或者ip段,語法如下:
deny IP; deny subnet; allow IP; allow subnet; # block all ips deny all; # allow all ips allow all;
如果規則之間有沖突,會以最前面匹配的規則為准。
配置禁用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配置節內添加下面一行配置:
include blockips.conf;
保存nginx.conf文件,然后測試現在的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
如果配置有問題就需要檢查下哪兒有語法問題,如果沒有問題,需要執行下面命令,讓nginx重新載入配置文件。
/usr/local/nginx/sbin/nginx -s reload
僅允許內網ip
如何禁止所有外網ip,僅允許內網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,允許其他內網網段,然后deny all禁止其他所有ip。
格式化nginx的403頁面
如何格式化nginx的403頁面呢?
首先執行下面的命令:
cd /usr/local/nginx/html vi error403.html
然后輸入403的文件內容,例如:
<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配置節內添加下面內容。
# redirect server error pages to the static page error_page 403 /error403.html; location = /error403.html { root html; }
然后保存配置文件,通過nginx -t命令測試配置文件是否正確,若正確通過nginx -s reload載入配置。
摘自: 忠碼一生