Nginx 配置 ngx_http_auth_basic_module 认证访问 Web

在互联网分享时代,我们使用Nginx建立了一个网站、一个网络目录;但是有的时候这些东西我只想分享给熟悉的人,不想让其他人访问。虽然现在有很多的开源程序,方法可以做到我所有的要求。但是我就是喜欢折腾。现在就利用 Nginx 的 ngx_http_auth_basic_module 模块配置一个网页的认证登录。只有输入正确账号和密码才可以访问。如下图,访问网站时提示需要授权;

nginx请求头host_nginx请求头host

lnmp1.6 的 Nginx 1.16.1默认已经编译了 ngx_http_auth_basic_module 模块,访问的账号和密码需要  httpd-tools 来生成,所以只需要安装 httpd-tools 和简单的配置 Nginx Conf 即可实现以上的效果。

0x01 确认是否安装 httpd-tools

  1. cd / # 进入根目录;
  2. rpm -qa | grep httpd # 检查 httpd-tools 版本,如果已经安装则回显版本信息;
  3. yum -y install httpd-tools # 如果没有安装,执行此命令进行安装;

nginx请求头host_nginx_02

nginx请求头host_nginx_03

0x02 创建授权用户和密码

安装完httpd-tools后使用 htpasswd 来生成授权用户和密码;

  1. mkdir /user # 在根目录创建一个 user 的目录存放 htpasswd 生成用户和密码文件,也可以放在其他地方;
  2. htpasswd -c -d /user/uwd_file pangzhan # htpasswd 创建一个名为uwd_file的文件,增加用户pangzhan,根据提示输入两次密码;
  3. htpasswd -d /user/uwd_file test # 创建第二个用户test,根据提示输入两次密码,多个用户以此类推;
  4. htpasswd -d /user/uwd_file pangzhan # 重置用户 pangzhan 的密码,注意参数的大小写;
  5. htpasswd -D /user/uwd_file test # 删除用户 test 注意参数的大小写;

nginx请求头host_linux_04

nginx请求头host_linux_05

htpasswd 参数解释:

  • -c Create a new file. # 创建一个新文件。
  • -n Don’t update file; display results on stdout. # 不要更新文件; 显示输出结果。
  • -b Use the password from the command line rather than prompting for it. # 使用命令行中的密码而不是提示输入密码。
  • -i Read password from stdin without verification (for script usage). # 从stdin读取密码而不进行验证(用于脚本)。
  • -m Force MD5 encryption of the password (default). # 强制密码的MD5加密(默认)。
  • -B Force bcrypt encryption of the password (very secure). # 强制密码加密(非常安全)。
  • -C Set the computing time used for the bcrypt algorithm (higher is more secure but slower, default: 5, valid: 4 to 31).
    # 设置用于bcrypt算法的计算(更高更安全但更慢,默认值:5,有效:4到31)
  • -d Force CRYPT encryption of the password (8 chars max, insecure). # 强制CRYPT加密密码(最多8个字符,不安全)
  • -s Force SHA encryption of the password (insecure). # 强制密码SHA加密(不安全)
  • -p Do not encrypt the password (plaintext, insecure). # 不加密密码(明文,不安全)
  • -D Delete the specified user. # 删除指定的用户
  • -v Verify password for the specified user. # 验证指定用户的密码。

0x03 配置 Nginx Conf 配置

将以下 ngx_http_auth_basic_module 配置参数,添加到站点 Nginx Conf 文件中

location / {
auth_basic “Test Nginx Basic Auth”; # 将 “Test Nginx Basic Auth” 改为 off 关闭认证,也可改为你想要的内容;
auth_basic_user_file /user/uwd_file; # 授权用户和密码文件的路径;
}

开启认证配置,并可以写认证标题

nginx请求头host_运维_06

关闭认证配置,将标题改为 off

nginx请求头host_运维_07