在Web应用中,对部分资源进行访问控制是是否常见的需求,Nginx的http auth模块以及Apache http auth都是很好的解决方案。
默认情况下nginx已经安装了ngx_http_auth_basic_module
模块,支持基于用户名和密码的基本认证。
nginxlocation /admin/ { auth_basic "Admin Area"; # 认证提示字符串(realm) auth_basic_user_file /etc/nginx/.htpasswd; # 密码文件路径 }
已安装Docker和Docker Compose
首先,创建一个项目目录并进入:
bashmkdir nginx-auth-basic && cd nginx-auth-basic
创建docker-compose.yml
文件:
yamlversion: '3.8'
services:
nginx:
image: nginx:latest
container_name: nginx_auth_basic
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html # 静态文件目录
- ./conf/nginx.conf:/etc/nginx/nginx.conf # 主配置文件(注意路径末尾无斜杠)
- ./conf/conf.d:/etc/nginx/conf.d # 子配置目录
- ./logs:/var/log/nginx # 日志目录
- ./htpasswd:/etc/nginx/htpasswd # 密码认证
restart: always
创建nginx.conf
文件:
nginxuser nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; }
创建conf.d/default.conf
文件:
nginxserver { listen 80; server_name localhost; location / { # 关键配置 auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/htpasswd/.htpasswd; root /usr/share/nginx/html; index index.html index.htm; } }
使用htpasswd
工具创建认证文件。
bashsudo yum install httpd -y
bashmkdir -p htpasswd
htpasswd -c ./htpasswd/.htpasswd username
bash# 添加用户
echo -n 'test:' >> ./htpasswd/.htpasswd
# 设置密码
openssl passwd 111111 >> ./htpasswd/.htpasswd
bashcat ./htpasswd/.htpasswd
运行以下命令启动Nginx
容器:
bashdocker-compose up -d
访问ngxin页面,会看到一个登录提示框,输入设置的用户名和密码才能访问页面:
登录之后
nginxlocation /public { root /usr/share/nginx/html; index index.html index.htm; } location /private { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/htpasswd/.htpasswd; root /usr/share/nginx/html; index index.html index.htm; }
nginxlocation /admin { auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/htpasswd-admin/.htpasswd; } location /users { auth_basic "User Area"; auth_basic_user_file /etc/nginx/htpasswd-users/.htpasswd; }
本文作者:哈希喵
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!