ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# location区块与访问控制 [TOC] ## 一、 Nginx的location区块 ### 1. 链接和简述 [官方文档](http://nginx.org/en/docs/http/ngx_http_core_module.html#location ) location指令通过作用是根据用户请求的URI来进行匹配,匹配成功就进行相应的操作,可以理解为shell中的if语句的作用 ### 2. location语法 ```sh location [ / = ~ ~* ^~ ] uri { ...... } ~ 表示区分大小写(正则) ~* 表示不区分大小写(正则) ^~ 只做常规字符串检查,不做正则检查 ! 逻辑取反操作符号 = 精确匹配 / 默认匹配 ``` ### 3. 匹配规则示例和优先级 1. `"location = / {"` 等号优先级最高,精确匹配/ 2. `"location ^~/images/ {"` ^~匹配常规字符串,不做正则检查,匹配/images/ 3. `"location ~* \.(gif|jpg)$ {"` 正则匹配,所以以gif/jpg结尾的uri 4. `"location /documents/ {"` 匹配常规字符串/documents/,优先级低于正则匹配, 5. `"location / {"` 默认匹配,所有location都不匹配后的默认匹配 ## 二、 [**ngx_http_access_module**]访问控制模块 ### 1. 链接和简述 [官网文档](nginx.org/en/docs/http/ngx_http_access_module.html ) 可以配合location模块实现对网段的访问控制 ### 2. 语法举例 ```sh location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all; } ``` ## 三、 访问控制企业案例 ### 1. 需求 搭建好一台nginx的web服务器。配置好内网卡地址与外网卡地址, web服务的网站域名为`www.etiantian.org`,站点目录为html/www. 1. 要求内网用户可以访问网站http://www.etiantian.org/AV资源信息 2. 要求外网用户禁止访问网站http://www.etiantian.org/AV资源信息 ### 2. 编写配置文件 ```sh server { listen 80; server_name www.etiantian.org; root html/www; index index.html index.htm; location /AV { allow 172.16.1.0/24; deny 10.0.0.0/24; } } ``` ### 3. 创建测试访问资源 ```sh mkdir AV echo "AV info" >AV/noah.html cat AV/noah.html ``` ### 4. 重启验证 ``` nginx -t nginx -s reload ``` ## 四、 访问认证[了解] **1. 示例** 可以通过为网站设置 访问账号和密码权限,进行访问认证,示例如下 ```sh location / { root html/www; index index.html index.htm; auth_basic "noah training"; auth_basic_user_file /app/nginx/conf/htpasswd; } ``` **2. 说明:** * auth_basic 开启认证和认证提示信息; 默认未开启,使用位置是http、server、location、limit_except * auth_basic_user_file 认证用的密码文件 密码文件要使用htpasswd命令创建,如果没有此命令需要安装,文件是加密的 **密码文件创建命令:** ```sh yum install httpd -y htpasswd -bc /app/nginx/conf/htpasswd noah 123456 chomod 400 /app/nginx/conf/htpasswd chown nginx /app/nginx/conf/htpasswd ```