基于Nginx的HTTP Basic认证服务

2024/05/26 | 字数845 | 阅读2分钟


本文讲述如何基于ubuntu系统 & nginx搭建一个基础的HTTP Basic Auth服务,可以用于为其他程序提供基于用户名和密码的认证服务,例如为gerrit提供登陆登出。这样当用户使用浏览器访问某个需要认证的URL地址的时候,就会弹出一个用户名和密码的对话框,要求用户输入验证信息,验证通过后才可以继续访问。这大概是最简单的认证机制了,如果需要的话,请继续往下看。

安装nginx

环境:ubuntu-24.04 ,nginx-1.24.0

bash
1
2
3
4
5
## 安装依赖工具
sudo apt install -y apache2-utils

## 安装nginx
sudo apt install -y nginx

配置用户名和密码

bash
1
2
3
4
5
6
7
8
## 创建一个密码文件/etc/nginx/.htpasswd,同时创建一个用户: ticktech,密码:ticktech123
sudo htpasswd -b -c /etc/nginx/.htpasswd ticktech ticktech123

## 继续创建一个用户: ticktechman,密码:ticktechman123
sudo htpasswd -b /etc/nginx/.htpasswd ticktechman ticktechman123

## 查看文件内容
sudo cat /etc/nginx/.htpasswd

配置nginx服务

cfg
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
## file: /etc/nginx/site-enabled/default
## 添加如下内容
server {
    listen 4080 default_server;        ## 这里配置端口,默认80
    listen [::]:4080 default_server;   ## 这里配置端口,默认80

    location /login {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        auth_basic "Gerrit Code Review";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

测试配置,重启服务

bash
1
2
sudo nginx -t -c /etc/nginx/nginx.conf
sudo service nginx restart

测试

打开浏览器,访问地址:http://192.168.1.107:4080/login(替换掉地址中的IP和端口为你的nginx服务器地址和端口),会出现下面图中的提示,输入用户名和密码后,正常访问网页了。

nginx-basic-auth

上一篇:我的视频制作工具箱 下一篇:喝杯咖啡,交个朋友

【文章不错,鼓励一下】