Nginx實現基於ip的訪問控制功能:(Ngx_http_access_module)
官方文檔:http://nginx.org/en/docs/http/ngx_http_access_module.html
官方示例:
The ngx_http_access_module module allows limiting access to certain client addresses.限定資源只被指定的客戶端訪問。
Example Configuration: location / { deny 192.168.1.1; #自上而下檢測,匹配範圍小的在上面 allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all; }
Syntax: | allow |
---|---|
Default: | — |
Context: | http , server , location , limit_except |
Syntax: | deny |
---|---|
Default: | — |
Context: | http , server , location , limit_except |
Context:適用配置段
演示環境:
Server:192.168.47.140 Client1:192.168.47.137 Client2:192.168.47.138 [root@GaoServer ~]# cat /etc/redhat-release CentOS Linux release 7.2.1511 (Core) [root@GaoServer ~]# uname -r 3.10.0-327.el7.x86_64 [root@GaoClient ~]# nginx -V nginx version: nginx/1.10.2 ......
相關配置:
#Server配置: [root@GaoServer ~]# cat /data/html/server/index.html <h1>192.168.47.140</h1> [root@GaoServer ~]# vim /etc/nginx/conf.d/Vhost.conf server { listen 80; location /server/ { root /data/html/; allow 192.168.47.137; #設定允許192.168.47.137 deny all; #拒絕所有 } } [root@GaoServer ~]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@GaoServer ~]# nginx -s reload #測試: #Client(192.168.47.137)訪問: [root@GaoClient1 ~]# ifconfig eno16777736 | grep "inet[[:space:]]" | sed 's/^.*et //g' | sed 's/netmask.*$//g' 192.168.47.137 [root@GaoClient1 ~]# curl http://192.168.47.140:/server/ <h1>192.168.47.140</h1> #Client(192.168.47.138)訪問: [root@GaoClient2 ~]# ifconfig eno16777736 | grep "inet[[:space:]]" | sed 's/^.*et //g' | sed 's/netmask.*$//g' 192.168.47.138 [root@GaoClient2 ~]# curl http://192.168.47.140:/server/ <html> <head><title>403 Forbidden</title></head> <body bgcolor="white"> <center><h1>403 Forbidden</h1></center> #403 Forbidden權限拒絕。 <hr><center>nginx/1.10.2</center> </body> </html>