Nginx权限配置需求:允许所有.htpasswd用户访问/protected、仅admin用户访问/admin
Nginx权限配置需求:允许所有.htpasswd用户访问/protected、仅admin用户访问/admin
嗨,针对你提出的权限配置需求,我来帮你梳理并给出可行的Nginx配置方案,完全匹配你的要求:
核心思路拆解
- 对于
/protected目录:只需要开启基础HTTP认证,让.htpasswd里的所有合法用户都能通过验证访问即可。 - 对于
/admin目录:在基础认证的基础上,额外增加一层用户身份校验,只有用户名是admin的用户才能通过,其他用户直接返回403禁止访问。
完整配置代码
location /protected { auth_basic "Protected Area"; auth_basic_user_file .htpasswd; root /static; autoindex_exact_size off; autoindex on; } location /admin { auth_basic "Restricted Area"; auth_basic_user_file .htpasswd; # 先初始化标记变量为非admin状态 set $is_admin 0; # 如果当前登录用户是admin,将标记改为1 if ($remote_user = "admin") { set $is_admin 1; } # 若标记仍为0,返回403禁止访问 if ($is_admin = 0) { return 403; } root /static; autoindex_exact_size off; autoindex on; } location / { root /static; autoindex_exact_size off; autoindex on; }
配置说明
/protected 配置:
auth_basic开启了基础认证,提示信息为"Protected Area"auth_basic_user_file指定了用户密码文件的路径,只要是这个文件里的合法用户,输入正确密码就能访问该目录。
/admin 配置:
- 同样先开启基础认证,确保只有
.htpasswd里的用户能进入校验环节 - 通过
set指令初始化变量$is_admin为0,代表非admin用户 - 利用
if判断当前登录的$remote_user是否为"admin",如果是则把$is_admin设为1 - 最后判断如果
$is_admin还是0,就返回403状态码,拒绝访问,这样就只有admin用户能进入该目录了。
- 同样先开启基础认证,确保只有
备注:内容来源于stack exchange,提问作者0minaway
相关产品推荐
相关产品推荐

