13. Nginx 访问认证
ngx_http_auth_basic_module 模块实现让访问者,只有输入正确的用户密码才允许访问web内容。
web上的一些内容不想被其他人知道,但是又想让部分人看到。nginx的http auth模块以及Apache http auth都是很好的解决方案。
默认情况下nginx已经安装了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 --without-http_auth_basic_module
# nginx 提供了认证模式,语法如下
location / {
auth_basic 'string'; # 开启认证功能,并自定义名称
auth_basic_user_file conf/htpasswd; # 配置一个认证密码文件
}
linux 提供了密码生成命令:htpasswd
htpasswd 是 Apache 提供的密码生成工具, nginx 也支持 auth_basic 模块,我们可以利用 htpasswd 命令生成账号密码文件提供给 nginx 使用
# 安装 htpasswd
yum install httpd-tools -y
# 语法
htpasswd -bc .access username password
# 解释:
-b 在命令行中输入账号密码
-c 创建密码文件
username 账号
password 密码
默认 .access 文件使用 md5 加密验证
# 创建密码文件
[root@nginx conf_file]# htpasswd -bc ./htpasswd demo 123
Adding password for user demo
[root@nginx conf_file]# ls -a
. .. htpasswd learn_rewrite.conf mylocation.conf port.conf test1_rewrite.conf
[root@nginx conf_file]# cat htpasswd
demo:$apr1$pYxCrJ0m$6PuPOIoPf856BzfJcsbL0.
- 案例测试
server {
listen 86;
server_name _;
location / {
root html/learn_auth;
index index.html;
auth_basic "learn nginx auth_basic"; #
auth_basic_user_file /usr/local/nginx/conf/conf_file/htpasswd;
}
}