zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Nginx访问路径添加密码保护

2023-03-07 09:40:11 时间

创建口令文件

用openssl命令创建口令

openssl passwd -apr1

会产生一个hash口令, 然后和用户名一起, 以[用户名]:[hash口令]的格式写入文本文件即可

例如创建一个名为 site_passwd 的文件, 放到nginx的conf目录的 htpasswd 目录下

mycat:$apr1$s2XP.Vxi$CWQHb8GDsPThsBR6HD4/F/
milton:$apr1$BZImjdgT$PJ9Dq08hwi5XrBxIHev/W/

如果有htpasswd命令, 也可以直接用下面的命令创建, 这个命令来自于 apache2-utils

htpasswd -c site_passwd mycat

 

Nginx配置文件修改

对于需要口令限制的目录, 创建一个单独的location (如果已经有, 则加在已经有的配置上). 例如这里限制的是demo这个路径下的访问. 对于前缀为/的location里的配置, 需要在这个location里重新填一遍, 配置了/demo后, /的配置在这个路径下不再起作用.

    location / {
        root   /var/wwwroot/site;
        index  index.html index.htm index.php;
    }

    location /demo {
        root   /var/wwwroot/site;
        index  index.html index.htm index.php;
        auth_basic "Restricted Content";
        auth_basic_user_file htpasswd/site_passwd;
    }

reload后访问就会弹出口令输入了.

sudo systemctl reload nginx