一、 Nginx的location区块

  1. 链接和简述
    官方文档
    location指令通过作用是根据用户请求的URI来进行匹配,匹配成功就进行相应的操作,可以理解为shell中的if语句的作用

  2. location语法

    location [ /  =  ~  ~*  ^~ ] uri { ...... }
    ~   表示区分大小写(正则)
    ~*  表示不区分大小写(正则)
    ^~  只做常规字符串检查,不做正则检查
    !   逻辑取反操作符号
    =   精确匹配
    /   默认匹配
  3. 匹配规则示例和优先级

    "location = / {"
    等号优先级最高,精确匹配/
    "location ^~/images/ {"
    ^~匹配常规字符串,不做正则检查,匹配/images/
    "location ~* \.(gif|jpg)$ {"
    正则匹配,所以以gif/jpg结尾的uri
    "location /documents/ {"
    匹配常规字符串/documents/,优先级低于正则匹配,
    "location / {"
    默认匹配,所有location都不匹配后的默认匹配

    二、 [ngx_http_access_module]访问控制模块

  4. 链接和简述
    官网文档
    可以配合location模块实现对网段的访问控制

  5. 语法举例

    location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
    }

    三、 访问控制企业案例

  6. 需求
    搭建好一台nginx的web服务器。配置好内网卡地址与外网卡地址, web服务的网站域名为www.etiantian.org,站点目录为html/www.

要求内网用户可以访问网站http://www.etiantian.org/AV资源信息
要求外网用户禁止访问网站http://www.etiantian.org/AV资源信息

  1. 编写配置文件
    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;
     }
    }
  2. 创建测试访问资源
    mkdir AV
    echo "AV info" >AV/noah.html
    cat AV/noah.html
  3. 重启验证
    nginx -t
    nginx -s reload
    四、 访问认证[了解]
  4. 示例
    可以通过为网站设置 访问账号和密码权限,进行访问认证,示例如下
 location / {
    root   html/www;
    index  index.html index.htm;
    auth_basic          "noah training";
    auth_basic_user_file /app/nginx/conf/htpasswd;
}
  1. 说明:

auth_basic 开启认证和认证提示信息;
默认未开启,使用位置是http、server、location、limit_except
auth_basic_user_file 认证用的密码文件
密码文件要使用htpasswd命令创建,如果没有此命令需要安装,文件是加密的
密码文件创建命令:

yum install httpd -y
htpasswd -bc /app/nginx/conf/htpasswd noah 123456
chomod 400 /app/nginx/conf/htpasswd
chown nginx /app/nginx/conf/htpasswd
文档更新时间: 2023-08-10 06:14   作者:月影鹏鹏
IT运维支持-AIWALY-月影工作室