在Nginx里给你的站点或者目录加个用户认证

在HTTP中,基本认证(Basic access authentication)是一种用来允许网页浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式。

常见的用户认证截图

ngx_http_auth_basic_module模块实现让访问着,只有输入正确的用户密码才允许访问web内容。web上的一些内容不想被其他人知道,但是又想让部分人看到。Nginx的http auth模块以及Apache http auth都是很好的解决方案。

默认情况下Nginx已经安装了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 --without-http_auth_basic_module

Nginx Basic HTTP authentication

Nginx的用户配置实例

复制代码
location / {
    auth_basic           "my site";
    auth_basic_user_file conf/htpasswd;
}

指令说明

auth_basic

  • 语法: auth_basic string | off;
  • 默认值: auth_basic off;
  • 上下文: http,server,location,limit_except

开启使用"HTTP基本认证"(HTTP Basic Authentication)协议的用户名密码验证。指定的参数被用作域。参数可以包含变量。参数off可以取消继承自上一个配置等级auth_basic指令的影响。参数off表示不开启HTTP基本认证。

另外auth_basic指定的字符串会在弹窗中显示。

auth_basic_user_file

  • 语法: auth_basic_user_file file;
  • 默认值: ---
  • 上下文: http,server,location,limit_except

指定保存用户名密码的文件。

参数file中可以包含变量。

保存用户名和密码的文件格式如下:

复制代码
# comment
name1:password1
name2:password2:comment
name3:password3

密码应该使用crypt()函数加密。可以用Apache HTTP Server发行包中的htpasswd命令或者openssl passwd来创建此类文件。

参数file可以是文件、相对路径的文件、绝对路径的文件。非绝对路径下,文件的位置是相对于nginx安装路径下的conf目录的。比如nginx的安装路径是/usr/local/nginx,则设置对应的路径举例说明如下:

复制代码
auth_basic_user_file htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/htpasswd
auth_basic_user_file conf/htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/conf/htpasswd
auth_basic_user_file /tmp/htpasswd;
# htpasswd在机器上的位置:/tmp/htpasswd

创建用户名为admin,密码为12345的示例如下:

htpasswd

复制代码
[root@test ~]# /opt/apache/bin/htpasswd -bdc htpasswd admin 12345
Adding password for user admin
[root@test ~]# cat htpasswd
admin:PbSRr7orsxaso

openssl passwd

复制代码
[root@test ~]# openssl passwd 12345
fIHcRVEKijgoM
[root@test ~]# echo "admin:fIHcRVEKijgoM" > htpasswd
[root@test ~]# cat htpasswd
admin:fIHcRVEKijgoM

当然也可以使用Web**在线htpasswd生成器**来生产用户名和密码字符串复制粘贴到文件中保存引用。

变量说明

$remote_user

为HTTP基本认证提供的用户名。例如上述示例中提到的用户admin。

在Nginx里给你的站点或者目录加个用户认证

相关推荐
蝎子莱莱爱打怪2 天前
Centos7中一键安装K8s集群以及Rancher安装记录
运维·后端·kubernetes
何中应2 天前
Nginx转发请求错误
前端·后端·nginx
DianSan_ERP3 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅3 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
不是二师兄的八戒3 天前
Linux服务器挂载OSS存储的完整实践指南
linux·运维·服务器
芝士雪豹只抽瑞克五3 天前
Nginx 高性能Web服务器笔记
服务器·nginx
zhangfeng11333 天前
趋动云 如何ssh登录 服务区 项目server
运维·人工智能·ssh
ZeroNews内网穿透3 天前
谷歌封杀OpenClaw背后:本地部署或是出路
运维·服务器·数据库·安全
失重外太空啦3 天前
nginx
运维·nginx