一、简介
在 nginx 下,提供了 ngx_http_auth_basic_module 模块实现让用户只有输入正确的用户名密码才允许访问web内容。默认情况下,nginx 已经安装了该模块。所以整体的一个过程就是先用第三方工具设置用户名、密码(其中密码已经加过密),然后保存到文件中,接着在 nginx 配置文件中根据之前事先保存的文件开启访问验证。
二、安装htpasswd工具并生成配置
yum -y install httpd-tools
# 设置用户名和密码,并把用户名、密码保存到指定文件中
mkdir -p /etc/nginx/conf.d/htpasswd
htpasswd -c /etc/nginx/conf.d/htpasswd/custom.passwd xxxxx #xxxx为用户名,交互输入密码,
# New password:
# Re-type new password:
# Adding password for user xxxxx
三、设置nginx配置文件
# 创建新的conf文件
vim /etc/nginx/conf.d/xxxx.com.conf
# 输入如下内容
server {
listen 443 ssl http2;
server_name xxxx.com;
index index.html index.htm;
ssl_certificate /root/.acme.sh/xxxx.com/fullchain.cer;
ssl_certificate_key /root/.acme.sh/xxxx.com/xxxx.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
access_log /etc/nginx/conf.d/logs/xxxx_access.log main;
error_log /etc/nginx/conf.d/logs/xxxx_error.log;
location / {
proxy_pass http://127.0.0.1:8080;
auth_basic "Please Input Password";
auth_basic_user_file /etc/nginx/conf.d/htpasswd/custom.passwd;
}
location ~ /\. {
deny all;
}
}
https证书生成请参考文章 利用acme.sh生成免费htts证书。
本文完。