Nginx服务--访问控制,身份验证登录

一.Nginx基于授权的访问控制概述

  • Nginx与Apache一样,可以实现基于用户权限的访问控制,当客户端想要访问相应的网站或者目录时,要求用户输入用户名和密码,才能正常访问
  • 配置步骤生成用户密码认证文件 ;修改主配置文件相对应的目录,添加认证配置项;重启服务,访问测试

手工编译安装Nginx服务

  • 解压缩包
[root@localhost mnt]# tar zxvf nginx-1.12.2.tar.gz -C /opt
  • 安装环境依赖包
[root@localhost nginx-1.12.2]# yum install gcc gcc-c++ pcre pcre-devel zlib-devel -y
  • 创建用户,不建立宿主文件,且不能再shell上登录
[root@localhost nginx-1.12.2]# useradd -M -s /sbin/nologin nginx
  • 配置,安装且编译
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module

make && make install
  • 建立执行程序的软链接
[root@localhost nginx-1.12.2]# ln -s /usr/local/nginx/sbin/* /usr/local/sbin
  • 优化nginx服务控制
//编译脚本,方便service管理nginx服务
vim /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 99 20
# description: Nginx Service Control Script
PROG="/usr/local/nginx/sbin/nginx"               //nginx主程序
PIDF="/usr/local/nginx/logs/nginx.pid"           //nginx的PID号

case "$1" in
 start)
        $PROG;;
 stop)
        kill -s QUIT $(cat $PIDF);;
 restart)
        $0 stop
        $0 start;;
 reload)
        kill -s HUP $(cat $PIDF);;
 *)
        exit 1
esac
exit 0

#添加执行权限

chmod +x /etc/init.d/nginx

#添加为系统服务

chkconfig --add nginx 

  • 关闭防火墙,开启服务
[root@localhost nginx-1.12.2]# systemctl stop firewalld.service 
[root@localhost nginx-1.12.2]# setenforce 0
[root@localhost nginx-1.12.2]# service nginx start
[root@localhost nginx-1.12.2]# netstat -ntap | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      41204/nginx: master 
[root@localhost nginx-1.12.2]#
  • 访问Nginx服务首页

  • 使用htpasswd生成用户认证文件
[root@localhost nginx-1.12.2]# yum install httpd-tools -y
[root@localhost nginx-1.12.2]# htpasswd -c /usr/local/nginx/passwd.db stu
New password:             //123456
Re-type new password:     //123456
Adding password for user stu
[root@localhost nginx-1.12.2]# chmod 400 /usr/local/nginx/passwd.db
[root@localhost nginx-1.12.2]# cat /usr/local/nginx/passwd.db 
stu:$apr1$XZMPbX9x$4gYkBAEuZ6LZL1v1v5mua/

  • 修改主配置文件,添加相应的认证配置项
[root@localhost nginx-1.12.2]# vim /usr/local/nginx/conf/nginx.conf

46             auth_basic "secret"                              //添加认证配置
 47             auth_basic_user_file /usr/local/nginx/passwd.db //添加
  • 重启服务并访问nginx服务
[root@localhost nginx]# service nginx start

发布了78 篇原创文章 · 获赞 5 · 访问量 2593

猜你喜欢

转载自blog.csdn.net/qq397750142/article/details/103664431