安全永久是第一位.

安装 httpd-tools

1
yum install -y  httpd-tools 

创建密码目录

1
mkdir -p /etc/nginx/

生成新的用户名和密码

可以创建多个用户和密码.

1
2
3
4
5
# admin 是你的帐号
# password 是你的密码
htpasswd -bc /etc/nginx/htpasswd.users admin password

htpasswd -bc /etc/nginx/htpasswd.users root password

查看用户名

1
2
3
cat /etc/nginx/htpasswd.users 
# admin:$apr1$9c2/hWtI$0CSGPb8xGTxbZ4CLOx2N3.
# root:$apr1$9c2/fsadfasf1213xGTxbZ4fas12311.

应用到nginx配置上

添加以下二行代码在 server节点上

1
2
auth_basic "Restricted Access";      # 验证
auth_basic_user_file /etc/nginx/htpasswd.users;    

也可以关闭

1
auth_basic off;      # 关闭验证

完整的配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
server {
    listen 80;
    server_name fs.com;
    access_log /usr/local/nginx/logs/data.log main;
    root /data/wwwroot/mywww;
    auth_basic "Restricted Access";      # 验证
    auth_basic_user_file /etc/nginx/htpasswd.users;             # 验证文件
    location / {
     
   }
}

问题

1
2
nginx: [emerg] unknown directive "auth_basic " in /usr/local/nginx/conf/vhost/prometheus.conf:4
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed