Nginx download 配置basicauth

314 阅读1分钟

前言

在日常项目使用中,我们会使用Nginx来搭建网站,为客户提供文件下载。但是往往搭建后都是无认证了,对于一些保密文件无法提供有效保护。

措施

nginx中ngx_http_auth_basic_module模块实现让访问者提供正确的密码才能下载。 默认情况下Nginx已经安装了ngx_http_auth_basic_module模块。

语法简介

auth_basic string | off; #默认是off
auth_basic_user_file fileName;

生成密码

# ubuntu
sudo apt install apache2-utils
htpasswd -c -d /path/secretfile  username # -c 会覆盖掉之前生成的用户
htpasswd -b -d /path/secretfile  username password123 # -b 不会覆盖直接的用户,密码需要直接跟在用户名后面

#centos7
sudo yum install httpd-tools -y
htpasswd -c -d /path/secretfile username

nginx 配置

......
location /download {
               autoindex on;
               alias path;
               autoindex_exact_size off;
               autoindex_localtime on;
               auth_basic "username"; # username 根据加密的用户来配置
               auth_basic_user_file /path/secretfile;
               if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|md|html|htm|list|repo)$){
                      add_header Content-Disposition: 'attachment;';
               }  
        }
......

最后重启nginx即可完成配置生效。