我们经常要对网站资源进行控制访问,比如说,公司要求,只有采用内存才能访问公司内部资料,如果用外网是禁止访问的,这样就能很好的对重要资源进行保密控制与限制访问,为满足这一需求,nginx中location区块可以用于定位或者匹配网站资源信息。
当前环境:内网IP:172.16.1.31 外网IP:10.0.0.31
要求内网用户可以访问网站http://www.daydayup.com/res资源信息
要求外网用户禁止访问网站http://www.daydayup.com/res资源信息
- 编辑 www.conf 配置
[root@NFS extra]# vim www.conf server { server { listen 80; server_name www.daydayup.com; root html/www; index index.html index.htm; location /res { allow 172.16.1.0/24; #允许172.16.1.0/24 访问 deny 10.0.0.0/24; #禁止 10.0.0.0/24 访问 } }
location / {
deny 192.168.1.1; #禁止具体IP
allow 192.168.1.0/24; #允许内网网段
allow 10.1.1.0/16; #允许外网网段
allow 2001:0db8::/32; #允许IPV6
deny all; #禁止所有
}
-
创建文件夹res以及index.html文件
[root@NFS nginx]# mkdir html/www/res [root@NFS nginx]# echo "为道日损">html/www/res/index.html [root@NFS nginx]# cat html/www/res/index.html 为道日损 [root@NFS nginx]#
-
重启Nginx服务
[root@NFS nginx]# sbin/nginx -s reload
-
内网测试与外网测试。
内网:[root@NFS nginx]# curl www.daydayup.com 10.0.0.31 www.daydayup.com [root@NFS nginx]# curl www.daydayup.com/res/index.html 为道日损 [root@NFS nginx]#
外网:
附:
location区块进行定位站点目录下资源信息
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
官方链接:http://nginx.org/en/docs/http/ngx_http_core_module.html#location
location [ = | ~ | ~* | ^~ ] uri { ... }
= --- 精确匹配网站uri资源信息
~ --- 区分大小写匹配网站uri资源信息
~* --- 不区分大小写匹配网站uri资源信息
^~ --- 优先匹配网站uri资源信息
/res/ --- 指定匹配网站资源目录信息
/ --- 默认匹配网站资源信息
! --- 对匹配的内容进行取反
location = / {
[ configuration A ] --- 优先级最高 ①
}
location / { --- 所有匹配都不满足时候,匹配默认location ④
[ configuration B ]
}
location /documents/ { --- 根据资源目录进行匹配 ③
[ configuration C ]
}
location ^~ /images/ { --- 优先匹配 ②
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ { --- 不区分大小写匹配网站资源 ③
[ configuration E ]
}

