参考资料

  1. nginx配置文件详解
  2. Nginx如何用于反向代理?
  3. Cache-Control头设置max-age和immutable属性
  4. Nginxgzip开启压缩及相关配置详细说明以及案例
  5. Nginx如何设置防篡改?
  6. Nginxallow、deny:IP访问控制模块详细说明以及案例
  7. Nginx编译安装详细说明以及案例
  8. Nginx用户cookie模块详细说明以及案例

如何配置Nginx用户认证?

  1. 安装htpasswd工具(Apache工具包):

    • Ubuntu/Debian: sudo apt-get install apache2-utils

    • CentOS/RHEL: sudo yum install httpd-tools

  2. 创建密码文件:

    sudo htpasswd -c /etc/nginx/.htpasswd username
  3. 编辑Nginx配置文件(通常在/etc/nginx/sites-available/default/etc/nginx/conf.d/default.conf):

    server {
        listen 80;
        server_name example.com;
    
        location / {
            auth_basic "Restricted Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }
    }
  4. 测试并重载Nginx配置:

    sudo nginx -t
    sudo systemctl reload nginx

完整示例:

server {
    listen 80;
    server_name mysite.com;

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

        # 其他配置
        proxy_pass http://localhost:8080;
    }
}