nginx通过 auth_basic和auth_basic_user_file配置密码保护。

auth_basic 字段是用户名、密码弹框上显示的文字

auth_basic_user_file指定了记录登录用户名与密码的文件 share.db,这个文件需要使用 htpasswd 命令或者在线工具来生成

htpasswd 命令是 MacOS 系统自带的命令,建议直接使用在线生成工具比较方便。

  • htpasswd操作命令
#创建一个全新的文件,会清除文件里的全部用户
htpasswd -c /usr/local/nginx-1.6.3/http/share.db user1  
#添加一个用户,如果用户已存在,则修改密码
htpasswd -b /usr/local/nginx-1.6.3/http/share.db user2 password
#删除一个用户
htpasswd -D /usr/local/nginx-1.6.3/http/share.db user2
  • 完整配置
	server {
  		listen 80;
  		server_name book.gophper.com;
  		root  /opt/share/book;
  		index index.html index.htm;
  		error_page 500 502 503 504 /50x.html;
  		location / {
  		    auth_basic "登录校验";
  		    auth_basic_user_file /usr/local/nginx-1.6.3/http/share.db;
  		    fancyindex on;
  		    fancyindex_exact_size off;        	       
  		    fancyindex_localtime on;
  		    fancyindex_name_length  100;
  		    charset utf-8,gbk;
  		}
	}