1、启动Nginx服务
systemctl start nginx.service
2、使用htpasswd工具生成密码
yum -y install httpd-tools
#安装htpasswd工具
cd /etc/nginx/
#切换目录
htpasswd -c ./auth wen
#使用htpasswd命令在当前目录创建一个名为auth的文件,用户为wen
回车后需要输入两次密码
more ./auth
#查看auth文件里的内容,有用户名和加密的字符串
2、修改Nginx配置文件
vim /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /opt/server;
index index.html index.htm;
}
location ~ ^/auth.html {
root /opt/app/code;
auth_basic "Auth access test!input your passward!";
auth_basic_user_file /etc/nginx/auth;
index index.html index.htm;
}
3、到相应路径下创建一个名为auth.html的HTML文件
vim /opt/app/code/auth.html
<html>
<head>
<meta charset="utf-8">
<title>wen</title>
</head>
<h1>通过用户登录认证</h1>
</body>
</html>
4、检查Nginx的配置语法并重新加载服务
nginx -tc /etc/nginx/conf.d/default.conf
nginx -s reload -c /etc/nginx/conf.d/default.conf
5、浏览器访问 ip/auth.html ,弹出窗口要求输入用户名和密码则是刚刚使用htpasswd工具时所创建的用户和密码。输入正确的用户名和密码后,就会跳转到auth.html页面内内容