HTTP验证

下载安装 htpasswd

1
2
3
4
5
6
apt install apache2-utils -y

# 生成密码文件
htpasswd -c -d /etc/nginx/.htpasswd user # user 是用户名
# 输入密码

生成的密码文件

1
2
# htpasswd
users:$apr1$ZQx2j8wN$2eqFlYE6fVnK/a8dQsAOZ/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
events {}

http {
server {
listen 443 ssl; # 这是HTTPS的默认端口,80为HTTP的默认端口
server_name nginx.baby; # 填写绑定证书的域名

ssl_certificate /etc/nginx/ssl/nginx.baby.pem; # 证书文件位置(.crt文件, .pen文件)
ssl_certificate_key /etc/nginx/ssl/nginx.baby.key; # 私钥文件位置(.key文件)

location / {
# auth_basic "请输入用户名密码"; # 提示,可省略
# auth_basic_user_file /etc/nginx/.htpasswd; # 密码文件位置(.htpasswd文件)

root /usr/share/nginx/html;
index index.html;
}
}
server {
listen 80;
return 301 https://$host$request_uri; # 将HTTP请求全部重定向到HTTPS
}

}

Docker 容器的 nginx 配置

1
2
3
4
5
6
7
8
9
docker run -itd \
--name test_nginx_ssl \
--restart unless-stopped \
-p 80:80 -p 443:443 \
-v /apps/htpass/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /apps/htpass/htpasswd:/etc/nginx/.htpasswd:ro \
-v /apps/htpass/html:/usr/share/nginx/html:ro \
-v /apps/htpass/ssl:/etc/nginx/ssl:ro \
nginx