Nginx为网站或目录添加用户认证

2022-08-26

需求

通过调整Nginx服务端配置,实现目标:

访问Web页面的时候需要进行用户认证。(此页面开启了目录浏览,有加密文件)

配置文件

Nginx配置文件修改

server {
    listen 443 ssl;
--------------

    location /encryfile {
        root /data;
    	autoindex on;
    	autoindex_format html;
    	autoindex_exact_size off;
    	autoindex_localtime on;
    	charset utf-8,gbk;

	auth_basic "auth-domain";
        auth_basic_user_file /usr/local/nginx/pass;
        }
        }

注意

此处是给特定目录添加认证,将认证写入了location段中,访问目录其他文件的时候是可以直接访问的。

如果是给location中~ ^/encryfile/.*添加认证,那就是保护encryfile目录下所有文件

配置段

用户认证的配置段:http, server, location, limit_except

生成密码文件

httpd-tools

# 安装httpd-tools
yum install httpd-tools -y


# 生成密码文件,创建用户和密码
htpasswd -c /usr/local/nginx/pass admin # pass为密码文件,admin是用户名

# htpasswd其他参数:
-c 创建passwdfile.如果passwdfile 已经存在,那么它会重新写入并删去原有内容.
-n 不更新passwordfile,直接显示密码
-m 使用MD5加密(默认)
-d 使用CRYPT加密(默认)
-p 使用普通文本格式的密码
-s 使用SHA加密
-b 命令行中一并输入用户名和密码而不是根据提示输入密码,可以看见明文,不需要交互
-D 删除指定的用户

perl脚本

如果不想安装httpd-tools,可以用perl脚本来实现:

#! /usr/bin/perl -w  

#filename: add_ftp_user.pl  

use strict;  

#  

print "#example: user:passwd\n";  

while (<STDIN>) {  

  exit if ($_ =~/^\n/);  

  chomp;  

  (my $user, my $pass) = split /:/, $_, 2;  

  my $crypt = crypt $pass, '$1$' . gensalt(8);  

  print "$user:$crypt\n";  

}  

sub gensalt {  

  my $count = shift;  

  my @salt = ('.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z');  

  my $s;  

  $s .= $salt[rand @salt] for (1 .. $count);  

  return $s;  

} 

脚本使用:

# 为脚本添加执行权限
chmod +x add_user.pl

# 脚本使用
./add_user.pl
user:password
# 把生成的用户名密码粘贴到密码文件中即可

重启Nginx访问

Nginx -s reload

image.png

其他操作

1、如何在原有密码文件中增加下一个用户?

htpasswd -b pass user1 123456

一定要去掉-c选项,否则覆盖密码文件再创建

2、htpasswd命令删除用户名和密码?

htpasswd -D pass user1

3、修改密码

htpasswd -D pass 123456

标题:Nginx为网站或目录添加用户认证
作者:lianglaifu
地址:https://llfu.life/articles/2022/08/26/1661497794358.html