十八.搭建Nginx服务器、配置网页认证、基于域名的虚拟主机、ssl虚拟主机

时间:2022-06-18 17:12:18

配置要求:

client:192.168.4.10
proxy:192.168.4.5(eth0) 192.168.2.5(eth1)
web1:192.168.2.100
web2:192.168.2.200
 
1.1 搭建nginx服务器
proxy:
]# yum -y install gcc pcre-devel openssl-devel
]# useradd -s /sbin/nologin nginx
]# ./configure \(安装包内)
> --prefix=/usr/local/nginx \
> --user=nginx  \
> --group=nginx \
> --with-http_ssl_module //开启SSL加密功能
]# make && make install
]# systemctl stop httpd
]# systemctl disable httpd
]# ln -s /usr/local/nginx/sbin/nginx /sbin/
]# nginx
]# netstat -anptu | grep nginx
 
1.2 升级nginx服务器
]# nginx -s  stop
]# mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
]# ./configure  \
> --prefix=/usr/local/nginx \ 
> --user=nginx  \ 
> --group=nginx \ 
> --with-http_ssl_module
]# make && make install
]# cp objs/nginx /usr/local/nginx/sbin/(安装包内)
]# make upgrade  //升级
]# nginx
]# nginx -V
client 测试:
]# firefox http://192.168.4.5
 
2. 配置用户认证
]# vim /usr/local/nginx/conf/nginx.conf
...
server_name  localhost;
     auth_basic "Input Password";
     auth_basic_user_file "/usr/local/nginx/pass";
...
]# yum -y install httpd-tools
]# htpasswd -c /usr/local/nginx/pass tom1
]# htpasswd /usr/local/nginx/pass    tom2  //追加用户,不使用-c选项
]# cat /usr/local/nginx/pass
tom1:$apr1$2kaE07z6$vhGcS7rLiyIZrvsOIV8Zs0
tom2:$apr1$ob0nlqNt$o5Sb1PNK3RkbqRW73.kBB/
]# nginx -s reload
client测试:
]# firefox http://192.168.4.5(要输入账户、密码)
 
3.基于域名的虚拟主机
]# vim /usr/local/nginx/conf/nginx.conf
www.a.com 配置了用户认证
server {
    listen       80;
    server_name  www.a.com;
    auth_basic "Input Password";
    auth_basic_user_file "/usr/local/nginx/pass";
       
    location / {
        root   html;
        index  index.html index.htm;
    }
 
www.b.com 未配置用户认证
erver {
    listen       80;
    server_name  www.b.com;
 
    location / {
        root   www;
        index  index.html index.htm;
    }
]# mkdir /usr/local/nginx/www
]# echo "www" > /usr/local/nginx/www/index.html
]# nginx -s reload
client测试:
]# vim /etc/hosts
192.168.4.5   www.a.com  www.b.com
]# firefox http://www.a.com (输入用户名,密码访问)
]# firefox http://www.b.com;
 
4.SSL虚拟主机
]# cd /usr/local/nginx/conf
]# openssl genrsa > cert.key //生成私钥
]# openssl req -new -x509 -key cert.key > cert.pem //生成证书
]# ls
cert.key  cert.pem ...
]# vim /usr/local/nginx/conf/nginx.conf
 server {
    listen       443 ssl;
    server_name  www.c.com;
 
    ssl_certificate      cert.pem;
    ssl_certificate_key  cert.key;
 
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
 
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;
 
    location / {
        root   html;
        index  index.html index.htm;
        }
    }
]# nginx -s reload
client:
]# vim /etc/hosts
192.168.4.5 www.a.com  www.b.com  www.c.com
]# firefox https://www.c.com //信任证书后可以访问