如何在 Nginx 中使用 auth_basic 进行简单而有效的访问控制

🌟🌌 欢迎来到知识与创意的殿堂 — 远见阁小民的世界!🚀
🌟🧭 在这里,我们一起探索技术的奥秘,一起在知识的海洋中遨游。
🌟🧭 在这里,每个错误都是成长的阶梯,每条建议都是前进的动力。
🌟🧭 在这里,我们一起成长,一起进步,让我们在知识的世界里畅游无阻,共同创造一个充满智慧和创新的明天。
🌟📚 点击关注,加入我们的技术探索之旅吧!❤️📖✨
✨博客主页:远见阁小民的主页
📕本文专栏:前端专栏
📕其他专栏:后端专栏 AI专栏 Python专栏 其他专栏 白帽学徒笔记
Linux专栏 问题专栏

  使用 auth_basic 进行访问控制可以解决多种场景下的安全需求问题,在企业内部系统中,有些页面或资源只允许内部员工访问,使用 auth_basic 可以快速实现这种限制。
   下面我们来做个简单的示例👇

1 安装 httpd-tools

sudo yum install httpd-tools

2 生成 .htpasswd 文件

htpasswd -c ./nginx/.htpasswd fenglm

在这里插入图片描述

2.1 查看.htpasswd密码文件

我们发现密码是加密的

在这里插入图片描述

3 部署Nginx

这里我是使用docker安装的nginx,大家也可以用其他方式,都可以

3.1 编写docker-compose.yml文件

version: "3"
services:
  nginx:
    restart: always
    image: nginx:stable
    ports:
      - "80:80"
    volumes:
      - ./nginx/html/dist:/usr/share/nginx/html
      - ./nginx/www:/var/www
      - ./nginx/logs:/var/log/nginx
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/.htpasswd:/etc/nginx/.htpasswd

3.2 编写nginx.conf配置文件

重点在这里哦👇
auth_basic “Restricted Content”;
auth_basic_user_file /etc/nginx/.htpasswd;

worker_processes  1;
  
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''  close;
    }
    server {
        listen       80;
        server_name 62.234.25.218;

        location / {
            auth_basic "Restricted Content";
            auth_basic_user_file /etc/nginx/.htpasswd;

            root   /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

3.3 运行效果

在这里插入图片描述

4 扩展

4.1 添加或更新用户或更新现有用户的密码

注意:更新 .htpasswd 文件后,需要重启 Nginx 使其生效

htpasswd ./nginx/.htpasswd fenglm

4.2 删除用户

htpasswd -D /path/to/.htpasswd 用户名
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

远见阁

你的鼓励就是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值