插件窝 干货文章 Nginx如何配置用户验证页面

Nginx如何配置用户验证页面

Nginx htpasswd 配置 Basic 735    来源:    2025-04-27

Nginx 用户验证页面配置指南

Nginx 可以通过 HTTP 基本认证(Basic Authentication)来配置用户验证页面,保护特定的目录或网站。以下是详细的配置步骤:

1. 创建密码文件

首先需要创建一个包含用户名和密码的文件:

sudo sh -c "echo -n 'username:' >> /etc/nginx/.htpasswd"
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

或者使用 htpasswd 工具(需要安装 apache2-utils):

sudo apt-get install apache2-utils  # Debian/Ubuntu
sudo yum install httpd-tools        # CentOS/RHEL

sudo htpasswd -c /etc/nginx/.htpasswd username

要添加更多用户(不覆盖现有文件):

sudo htpasswd /etc/nginx/.htpasswd anotheruser

2. 配置 Nginx

在 Nginx 配置文件中添加认证配置:

保护整个网站

server {
    listen 80;
    server_name example.com;

    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;

    location / {
        # 其他配置...
    }
}

保护特定目录

server {
    listen 80;
    server_name example.com;

    location / {
        # 主站点配置...
    }

    location /protected/ {
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/.htpasswd;

        # 其他配置...
    }
}

保护特定文件类型

location ~ \.php$ {
    auth_basic "PHP Files Protected";
    auth_basic_user_file /etc/nginx/.htpasswd;

    # PHP处理配置...
}

3. 测试并重载配置

sudo nginx -t  # 测试配置语法
sudo systemctl reload nginx  # 或 sudo service nginx reload

高级选项

排除某些路径

location /protected/ {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    location /protected/public/ {
        auth_basic off;
    }
}

结合 IP 限制

location /admin/ {
    satisfy all;  # 需要同时满足IP和认证

    allow 192.168.1.0/24;
    deny all;

    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

使用不同的认证领域

auth_basic_user_file /etc/nginx/.htpasswd;
auth_basic "Different Realm Name";

注意事项

  1. 基本认证是明文传输的(Base64编码),建议在 HTTPS 下使用
  2. 密码文件应放在非 web 可访问的目录
  3. 定期检查密码文件的权限(建议 640 或 600)
  4. 对于更复杂的需求,可以考虑使用其他认证方式如 OAuth、JWT 等

这样配置后,访问受保护的页面时浏览器会弹出登录对话框,要求输入用户名和密码。