在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里给你的站点或者目录加个用户认证

相关推荐
Mr.亮先生10 分钟前
常用、高效、实用的 Linux 服务器监控与运维工具清单
linux·运维·服务器
极客先躯1 小时前
高可用巡检脚本实战:一键掌握服务、网络、VIP、资源状态
运维·网络·金融
鹿鸣天涯1 小时前
Wine 10.15 发布!Linux 跑 Windows 应用更丝滑了
linux·运维·windows
Lynnxiaowen2 小时前
今天我们继续学习python3编程之python基础
linux·运维·python·学习
Do_GH3 小时前
【Docker】06.通过WSL部署Docker Desktop
运维·docker·容器
siriuuus3 小时前
Nginx IP 透传
网络·nginx
40kuai3 小时前
nginx server_tokens 和proxy_hide_header的差别
运维·nginx
潇湘梦3 小时前
centOS防火墙操作
linux·运维·centos
奥尔特星云大使4 小时前
详细的Linux系统更新yum源的教程
linux·运维·服务器·ubuntu·centos·yum源·epel源
tritone4 小时前
在优豆云免费云服务器上初探SSH与SCP的便捷操作
运维·服务器·ssh