Nginx如何对目录进行访问控制【附代码】

今天爱分享给大家带来Nginx如何对目录进行访问控制【附代码】,希望能够帮助到大家。

[root@minglinux-01 ~] vim /usr/local/nginx/conf/vhost/test.com.conf
···
 33     location /admin/
 34     {
 35     allow 192.168.162.130;
 36     allow 127.0.0.1;
 37     deny all;      // 顺序执行规则,某条规则执行后,后面的规则不在执行
 38     }   
 39     
···

作用:访问/admin/目录的请求,只允许某几个IP访问

配置httpd的时候,有一个order,来定义先allow还是先deny,在Nginx里并没有,只要匹配到规则就结束了。

测试结果:

[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -s reload
[root@minglinux-01 ~] tail -2 /tmp/test.com.log
127.0.0.1 - [28/Nov/2018:21:19:08 +0800] test.com "/admin/admin.php" 200 "-" "curl/7.29.0"
192.168.162.130 - [28/Nov/2018:21:19:57 +0800] test.com "/admin/admin.php" 200 "-" "curl/7.29.0"
[root@minglinux-01 ~] curl -x192.168.162.135:80 test.com/admin/admin.php -I   //用另一个网卡IP访问不了
HTTP/1.1 403 Forbidden
Server: nginx/1.12.2
Date: Wed, 28 Nov 2018 13:32:26 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
[root@minglinux-01 ~] tail -3 /tmp/test.com.log
127.0.0.1 - [28/Nov/2018:21:19:08 +0800] test.com "/admin/admin.php" 200 "-" "curl/7.29.0"
192.168.162.130 - [28/Nov/2018:21:19:57 +0800] test.com "/admin/admin.php" 200 "-" "curl/7.29.0"
192.168.162.135 - [28/Nov/2018:21:32:26 +0800] test.com "/admin/admin.php" 403 "-" "curl/7.29.0"

人已赞赏
Nginx

Nginx 常用命令大全【详解】

2020-10-18 23:47:01

Nginx

Nginx配置文件nginx.conf详解 nginx的变量规则【附代码详解】

2020-10-19 18:10:43

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
'); })();