Administrator
发布于 2025-11-07 / 7 阅读
0
0

nginx用户认证配置(Basic HTTP authentication)

ngx_http_auth_basic_module模块实现让访问着,只有输入正确的用户密码才允许访问web内容。web上的一些内容不想被其他人知道,但是又想让部分人看到。nginx的http auth模块以及Apache http auth都是很好的解决方案。

默认情况下nginx已经安装了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 --without-http_auth_basic_module 。

生成账号密码文件(推荐安全写法)

# 创建存放认证文件的目录
sudo mkdir -p /etc/nginx/auth

# 方式一:兼容性更好的 Apache MD5 apr1 格式(推荐)
printf "admin:$(openssl passwd -apr1 'Strong_Passw0rd')\n" | sudo tee /etc/nginx/auth/htpasswd.guest

# 方式二:使用 Apache htpasswd(如可用,支持交互设置密码)
# sudo apt-get install -y apache2-utils
# sudo htpasswd -c /etc/nginx/auth/htpasswd.guest admin

nginx配置

保护整个server

server {
       listen 0.0.0.0:80;
       auth_basic             "admin auth";
       auth_basic_user_file   /etc/nginx/htpasswd;
       include proxy.conf;
}

仅保护 /internaldoc/

location /internaldoc/ {
  auth_basic "Restricted"; # 弹框标题
  auth_basic_user_file /etc/nginx/auth/htpasswd.guest; # 绝对路径
}

提示与注意:

  • 避免使用 openssl passwd -crypt(DES crypt,已不安全),改用 -apr1htpasswd

  • auth_basic_user_file 建议使用绝对路径,避免因工作目录变化导致找不到文件。

  • 若需保护整个站点,可将以上 location 改为 location /

  • Windows 环境同样可安装 OpenSSL 生成 apr1 格式;路径请改为适合本机的绝对路径。


评论