Nginx安装、用户认证、Nginx虚拟主机、https加密网站

494 阅读2分钟
搭建Nginx服务器

[root@localhost opt]# tar -xf lnmp_soft.tar.gz

//释放源码包

[root@localhost opt]# yum -y install gcc pcre-devel openssl-devel

//gcc是nginx的依赖包;pcre-devel可以让nginx支持正则;openssl-devel可以支持安全的加密网站

[root@localhost nginx-1.12.2]# ./configure --with-http_ssl_module

//在编译时添加安全模块

[root@localhost nginx-1.12.2]# make && make install

//安装

[root@localhost nginx]# sbin/nginx

//启动服务

[root@localhost nginx]# ss -ntulp |grep nginx tcp LISTEN 0 128 *:80 *:* users:(("nginx",pid=3953,fd=6),("nginx",pid=3952,fd=6))

//检测端口是否成功开启

测试

[root@localhost nginx]# systemctl stop firewalld

//关闭防护墙

//在浏览器输入本机ip地址,可以看到nginx的测试页面,即为成功

服务的控制

[root@localhost nginx]# sbin/nginx

//开启服务

[root@localhost nginx]# sbin/nginx -s stop

//关闭服务

[root@localhost nginx]# sbin/nginx -s reload

//重置服务;必须是服务开启状态(重新应用配置文件,但不关闭服务)


为网站添加认证功能

[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conf

//修改配置文件


 35     server {
 36         listen       80;
 37         server_name  localhost;
 38         auth_basic "请输入密码:";    #添加认证提示信息
 39         auth_basic_user_file "/usr/local/nginx/pass"; #添加认证用户文件位置
 40         #charset koi8-r;
 41         charset utf-8;
 42         #access_log  logs/host.access.log  main;
 43         
 44         location / {
 45             root   html;
 46             index  index.html index.htm;
 47         }
创建网站认证的用户名和密码文件

[root@localhost nginx]# yum -y install httpd-tools

//安装生成认证文件的工具

[root@localhost nginx]# htpasswd -c /usr/local/nginx/pass jerry New password: Re-type new password: Adding password for user jerry

//使用安装的工具创建pass文件,生成第一个用户

[root@localhost nginx]# sbin/nginx -s reload

//重置配置文件

测试

输入ip地址测试加密效果


创建nginx的虚拟主机

[root@localhost conf]# vim /usr/local/nginx/conf/nginx.conf

//修改配置文件

//一台主机就是一个server;监听端口80;

 35        listen        80;
 36        server_name   www.b.com;
 37        root          html_b;
 38        index         index.html   index.htm;
 39         }
 40     server {
 41         listen       80;
 42         server_name  www.a.com;
 43         location / {
 44             root   html;
 45             index  index.html index.htm;
 46         }
测试

创建页面进行测试,测试前修改本机hosts实现域名解析

[root@localhost nginx]# curl www.a.com

[root@localhost nginx]# curl www.b.com


搭建https加密网站

[root@localhost nginx]# vim conf/nginx.conf

//修改配置文件最后一页,删除关于安全网站的注释,cert.pem为公钥;cert.key为私钥

 96     # HTTPS server
 97     #
 98     server {
 99         listen       443 ssl;
100         server_name  localhost;
101 
102         ssl_certificate      cert.pem;
103         ssl_certificate_key  cert.key;
104 
105         ssl_session_cache    shared:SSL:1m;
106         ssl_session_timeout  5m;
107 
108         ssl_ciphers  HIGH:!aNULL:!MD5;
109         ssl_prefer_server_ciphers  on;
110 
111         location / {
112             root   html_b;
113             index  index.html index.htm;
114         }
115     }
116 
117 }
测试

[root@localhost nginx]# curl -k https://www.c.com web_c