Nginx Basic Auth 文件生成方式

方法1:通过 htpasswd 命令生成

先安装 htpasswd 命令:

Debian / Ubuntu

$ sudo apt update
$ sudo apt install -y apache2-utils

CentOS / RHEL

$ sudo yum install -y httpd-tools

然后生成文件:

$ sudo mkdir -p /etc/nginx/htpasswd
$ sudo htpasswd -c /etc/nginx/htpasswd/pushgateway your_username

系统会提示输入密码。

说明:

  • -c:创建新文件(如果文件已存在,不要再用 -c

  • 生成后的内容类似:

    your_username:$apr1$xxxxxxxx$xxxxxxxxxxxxxxxxxxxx
    

如果要添加第二个用户:

htpasswd /etc/nginx/htpasswd/pushgateway another_user

方法2:通过 openssl 命令生成

$ sudo mkdir -p /etc/nginx/htpasswd
$ sudo echo "your_username:$(openssl passwd -apr1 'your_password')" > /etc/nginx/htpasswd/pushgateway

验证是否有效

Nginx 配置示例:

location / {
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/htpasswd/pushgateway;
}

重载:

$ sudo nginx -t && sudo nginx -s reload
Author: ismdeep
License: Copyright (c) 2025 CC-BY-NC-4.0 LICENSE