一文吃透Nginx

更多内容请扫码关注公众号
在这里插入图片描述

文章目录

第一章 Nginx基础

1.1 Nginx简介

1.Nginx是什么
Nginx 是一个开源且高性能、可靠的 Http Web 服务、代理服务。
开源: 直接获取源代码
高性能: 支持海量并发
可靠: 服务稳定
配合PHP才能访问动态资源。

2.我们为什么选择 Nginx 服务
Nginx 非常轻量
功能模块少 (源代码仅保留 http 与核心模块代码,其余不够核心代码会作为插件来安装)
代码模块化 (易读,便于二次开发,对于开发人员非常友好)
互联网公司都选择 Nginx
    1.Nginx 技术成熟,具备的功能是企业最常使用而且最需要的
    2.适合当前主流架构趋势, 微服务、云架构、中间层
    3.统一技术栈, 降低维护成本, 降低技术更新成本。

3.Nginx重要特性
Nginx 采用 Epool 网络模型, Apache 采用 Select 模型
Select: 当用户发起一次请求, select 模型就会进行一次遍历扫描,从而导致性能低下。
Epool: 当用户发起请求, epool 模型会直接进行处理,效率高效,并无连接限制

1.2 Nginx应用场景

img

1.3 编译安装nginx

Nginx安装分为几种
1.源码编译(1.版本随意 2.安装复杂 3.升级繁琐)
2.epel仓库(1.版本较低 2.安装简单 3.配置不易读)
3.官方仓库(1.版本较新 2.安装简单 3.配置易读,推荐)

创建www用户

[root@web01 ~]# groupadd www -g 666
[root@web01 ~]# useradd www -s /sbin/nologin -M -u 666 -g 666
[root@web01 ~]# id www
uid=666(www) gid=666(www)=666(www)

安装依赖包

[root@web01 ~]# yum install openssl-devel pcre-devel gcc gcc+ -y

下载解压软件包

[root@web01 ~]# mkdir /data/soft -p
[root@web01 ~]# cd /data/soft/
[root@web01 /data/soft]# wget http://nginx.org/download/nginx-1.16.0.tar.gz
[root@web01 /data/soft]# tar zxvf nginx-1.16.0.tar.gz 

配置编译参数

[root@web01 ~]# cd /data/soft/nginx-1.16.0/
[root@web01 /data/soft/nginx-1.16.0]# ./configure --help
[root@web01 /data/soft/nginx-1.16.0]# ./configure --user=www --group=www --prefix=/opt/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module --with-pcre

--prefix=		#安装目录
--with-http_stub_status_module		#监控nginx状态
--with-http_ssl_module		 #支持https协议
--with-pcre		 #支持正则

编译安装

[root@web01 /data/soft/nginx-1.16.0]# make && make install

创建软链接

[root@web01 /data/soft/nginx-1.16.0]# ln -s /opt/nginx-1.16.0/ /opt/nginx
[root@web01 /data/soft/nginx-1.16.0]# ls -lh /opt/
总用量 4.0K
lrwxrwxrwx  1 root root   18 729 20:27 nginx -> /opt/nginx-1.16.0/
drwxr-xr-x 11 1001 1001 4.0K 729 20:26 nginx-1.16.0

检查语法

[root@web01 /opt/nginx]# /opt/nginx/sbin/nginx -t
nginx: the configuration file /opt/nginx-1.16.0//conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx-1.16.0//conf/nginx.conf test is successful

启动nginx与重新加载

[root@web01 /opt/nginx]# /opt/nginx/sbin/nginx				#启动 
[root@web01 /opt/nginx]# /opt/nginx/sbin/nginx -s reload	 #重新加载
[root@web01 /opt/nginx]# /opt/nginx/sbin/nginx -s stop		 #停止服务

检查测试

[root@web01 /opt/nginx]# netstat -lntup|grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      12828/nginx: master 
[root@web01 /opt/nginx]# curl 10.0.1.7

1.4 nginx官方仓库安装nginx

1.安装依赖
	yum install openssl-devel pcre-devel gcc gcc+ -y
2.配置官方yum源
[root@web01 ~]# vim /etc/yum.repos.d/nginx.repo
[root@web01 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
3.安装nginx服务
	[root@web01 ~]# yum install nginx -y
4.启动服务并配置开机自启动
    [root@web01 ~]# nginx -t		#必须是下面的提示才能启动nginx
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
    [root@web01 ~]# systemctl start nginx
    [root@web01 ~]# systemctl enable nginx
5.测试访问
	[root@web01 ~]# curl -I -s -w "%{http_code}\n" -o /dev/null 10.0.1.7

1.5 nginx启动管理方式

1.编译安装启动管理方式
nginx -t
nginx
nginx -s reload
nginx -s stop

2.yum安装启动管理方法(推荐)
nginx -t
systemctl start nginx
systemctl reload nginx
systemctl restart nginx
systemctl stop  nginx

1.6 Nginx配置文件

1.查看配置文件
[root@web01 ~]# rpm -ql nginx 
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
/etc/logrotate.d/nginx                     #nginx日志切割的配置文件
/etc/nginx/nginx.conf                      #nginx主配置文件 
/etc/nginx/conf.d                          #子配置文件
/etc/nginx/conf.d/default.conf             #默认展示的页面一样 
/etc/nginx/mime.types                      #媒体类型 (http协议中的文件类型)
/etc/sysconfig/nginx                       #systemctl 管理 nginx的使用的文件
/usr/lib/systemd/system/nginx.service      #systemctl 管理nginx(开 关 重启 reload)配置文件       
/usr/sbin/nginx                            #nginx命令
/usr/share/nginx/html                      #站点目录 网站的根目录 
/var/log/nginx                             #nginx日志 access.log 访问日志
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
2.查看nginx版本与编译模块
[root@web01 ~]# nginx -v
nginx version: nginx/1.16.1
[root@web01 ~]# nginx -V

01 Nginx主配置文件

配置文件注解
Nginx 主配置文件/etc/nginx/nginx.conf 是一个纯文本类型的文件,整个配置文件是以区块的形式组织的。一般,每个区块以一对大括号{}来表示开始与结束。主配置文件一般不动!!!☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
Nginx 主配置文件整体分为三块进行学习,分别是:
    1.CoreModule(核心模块)
    2.EventModule(事件驱动模块)
    3.HttpCoreModule(http 内核模块)
第一部分:配置文件主区域配置
user  nginx;                    		 			#定义运行nginx进程的用户
worker_processes  1;           			 			#Nginx运行的work进程数量(建议与CPU数量一致或 auto)

error_log  /var/log/nginx/error.log warn;             #nginx错误日志
pid        /var/run/nginx.pid;                        #nginx运行pid
第二部分:配置文件事件区域
events {
    worker_connections  1024;  #每个 worker 进程支持的最大连接数
}
第三部分:配置http区域
    http server location 扩展了解项
    http{}层下允许有多个 Server{}层,一个 Server{}层下又允许有多个 Location
    http{} 标签主要用来解决用户的请求与响应。
    server{} 标签主要用来响应具体的某一个网站。
    location{} 标签主要用于匹配网站具体 URL 路径

http {
    include       /etc/nginx/mime.types;          #Nginx支持的媒体类型库文件
    default_type  application/octet-stream;       #默认的媒体类型 

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '	#日志格式的名称是main
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;    #访问日志保存路径  日志格式main

    sendfile        on;                             #开启高效传输模式
    #tcp_nopush     on;                       
    keepalive_timeout  65;                          #连接超时时间
    gzip  on;                                       #开启压缩
    include /etc/nginx/conf.d/*.conf;               #包含子配置文件
}    
日志格式化(默认):参考11.9
$remote_addr 		访问的来源IP
- 
$remote_user 		远程访问 用户
[$time_local] 		访问时间
"$request" 			请求方式                 
$status 			访问状态
$body_bytes_sent 	 访问产生数据大小
"$http_referer" 	 记录当前页面是从哪个页面跳转过来的
                      
"$http_user_agent" 		请求的客户端是什么浏览器
"$http_x_forwarded_for";	负载均衡相关

02 Nginx子配置文件

子配置文件内容:sed -ri '/#|^$/d' *.conf
[root@web01 ~]# egrep -v "#|^$" /etc/nginx/conf.d/default.conf     
server {
    listen       80;             #指定监听端口
    server_name  localhost;      #指定监听的域名
    location / {              
        root   /usr/share/nginx/html;     #定义站点的目录
        index  index.html index.htm;      #定义首页文件
    }
    error_page   500 502 503 504  /50x.html;    #优雅显示页面信息
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
http server location 扩展了解项
http{}层下允许有多个 Server{}层,一个 Server{}层下又允许有多个 Location
http{} 标签主要用来解决用户的请求与响应。
server{} 标签主要用来响应具体的某一个网站。
location{} 标签主要用于匹配网站具体 URL 路径

03 基于域名实现的虚拟主机访问

#多个网站可以用放在同一个服务器上提供访问。
问题:只有一个IP地址,在浏览器输入IP,我找到了谁?
答案:当所有域名都匹配不上的时候,默认根据/etc/nginx/conf.d/下的子配置文件的文件名的ASCII码值排名去访问
[root@web01 /etc/nginx/conf.d]# ll *.conf
67922405 -rw-r--r-- 1 root root 155 2020-01-16 17:06:54 bbs.conf
67922402 -rw-r--r-- 1 root root 157 2020-01-16 17:07:03 blog.conf
67922404 -rw-r--r-- 1 root root 155 2020-01-16 17:07:16 www.conf
[root@web01 /etc/nginx/conf.d]# cat *.conf
server {
    listen       80;
    server_name  bbs.mysun.com;
    location / {
        root   /html/code/bbs;
        index  index.html index.htm;
    }
}
server {
    listen       80;
    server_name  blog.mysun.com;
    location / {
        root   /html/code/blog;
        index  index.html index.htm;
    }
}
server {
    listen       80;
    server_name  www.mysun.com;
    location / {
        root   /html/code/www;
        index  index.html index.htm;
    }
}
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
[root@web01 /html]# tree
.
└── code/
    ├── bbs/
    │   └── index.html
    ├── blog/
    │   └── index.html
    └── www/
        └── index.html

04 基于端口实现的虚拟主机访问

#端口号优先级比域名高
现象:如果输入IP+端口肯定能匹配到对应的内容,但是如果使用域名,匹配的不一定是自己想要的了,展现的内容主要看端口号来决定。所以端口号优先级比域名高。
[root@web01 /etc/nginx/conf.d]# cat *.conf
server {
    listen       8080;
    server_name  bbs.mysun.com;
    location / {
        root   /html/code/bbs;
        index  index.html index.htm;
    }
}
server {
    listen       8081;
    server_name  blog.mysun.com;
    location / {
        root   /html/code/blog;
        index  index.html index.htm;
    }
}
server {
    listen       8082;
    server_name  www.mysun.com;
    location / {
        root   /html/code/www;
        index  index.html index.htm;
    }
}

05 基于IP的虚拟主机访问

ip addr add 10.0.0.11/24 dev eth0	#添加第二个IP
root@web01 ~]# cat /etc/nginx/nginx.conf    

user  www;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

    #include /etc/nginx/conf.d/*.conf;
    server   {
        listen       10.0.1.7:81;
        server_name  www.mysun.com;
        location / {
            root   /usr/share/nginx/html/www;
            index  index.html index.htm;
        }
    }
    server   {
        listen       10.0.1.11:82;
        server_name  blog.mysun.com;
        location / {
            root   /usr/share/nginx/html/blog;
            index  index.html index.htm;
        }
    }
}

1.7 Nginx连环坑

1.基于端口的优先级高于域名
2.基于域名:当所有域名都匹配不上的时候,默认根据/etc/nginx/conf.d/下的子配置文件的文件名的ASCII码值排名去访问
3.IP+端口的优先级是最高的。
4.default_server指定默认匹配的页面,所有配置文件只能有一个。
server {
    listen       80 default_server;
    server_name  www.mysun.com;
    location / {
        root   /html/code/www;
        index  index.html index.htm;
    }
#小结:
1.如果是yum安装,启动关闭命令推荐使用systemctl。不要混着nginx -s这样用。
2.相同域名相同端口会报冲突,比如都是0.0.0.0:80
3.没有首页会报403而不是404
4.如果访问的域名全部都没有匹配上,那么会默认访问第一个网站,按照a-z顺序排列,如果想指定一个网站为首先跳转,可以配置文件名为01-www.conf类似或者在配置文件指定default_server。

1.8 Nginx状态模块

[root@web01 /etc/nginx/conf.d]# grep web01 /etc/hosts
10.0.1.7 172.16.1.7 web01 www.mysun.com blog.mysun.com bbs.mysun.com status.mysun.com
[root@web01 /etc/nginx/conf.d]# cat status.conf 
server {
   listen 80;
   server_name  status.mysun.com;
   stub_status on;
   access_log off;
}

1.9 Nginx日志

日志字段解释:
$remote_addr # 记录客户端 IP 地址
$remote_user # 记录客户端用户名
$time_local # 记录通用的本地时间
$time_iso8601 # 记录 ISO8601 标准格式下的本地时间
$request # 记录请求的方法以及请求的 http 协议
$status # 记录请求状态码(用于定位错误信息)
$body_bytes_sent # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent # 发送给客户端的总字节数
$msec # 日志写入时间。单位为秒,精度是毫秒。
$http_referer # 记录从哪个页面链接访问过来的
$http_user_agent # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端 IP 地址
$request_length # 请求的长度(包括请求行, 请求头和请求正文)。
$request_time # 请求花费的时间,单位为秒,精度毫秒
# :如果 Nginx 位于负载均衡器, nginx 反向代理之后, web 服务器无法直接获取到客 户端真实的 IP 地址。
# $remote_addr 获取的是反向代理的 IP 地址。 反向代理服务器在转发请求的 http 头信息中,
# 增加 X-Forwarded-For 信息,用来记录客户端 IP 地址和客户端请求的服务器地址。

1.10 Nginx日志切割

[root@web01 /etc/nginx/conf.d]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

第二章 Nginx常用模块

2.1 Nginx目录索引模块

官方文档:https://nginx.org/en/docs/http/ngx_http_autoindex_module.html

[root@web01 /etc/nginx/conf.d]# cp www.conf download.conf
[root@web01 /etc/nginx/conf.d]# cat download.conf 
server {
    listen       80;
    server_name  download.mysun.com;
    location / {
        autoindex on;
        root   /html/code/download;
        index  index.html index.htm;
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tq18CSLL-1586966855104)(C:\Users\17727\AppData\Roaming\Typora\typora-user-images\image-20200123225915213.png)]

上述页面有三个问题:
1.中文乱码
2.时间与系统时间不一致
3.文件大小不友好

Syntax: autoindex on | off;
Default: autoindex off;
Context: http, server, location

# autoindex 常用参数
autoindex_exact_size off;
默认为 on, 显示出文件的确切大小,单位是 bytes。
修改为 off,显示出文件的大概大小,单位是 kB 或者 MB 或者 GB。

autoindex_localtime on;
默认为 off,显示的文件时间为 GMT 时间。
修改为 on, 显示的文件时间为文件的服务器时间。

charset utf-8,gbk;
默认中文目录乱码,添加上解决乱码

2.2 状态监控模块

官方文档:https://nginx.org/en/docs/http/ngx_http_stub_status_module.html
[root@web01 /etc/nginx/conf.d]# cat status.conf 
server {
   listen 80;
   server_name  status.mysun.com;
   stub_status on;
   access_log off;
}

状态字段解释:
Active connections # 当前活动的连接数
accepts # 当前的总连接数TCP
handled # 成功的连接数TCP
requests # 总的http请求数
Reading # 请求
Writing # 响应
Waiting # 等待的请求数,开启了keepalive
# 注意:一次TCP的连接,可以发起多次http的请求, 如下参数可配置进行验证
keepalive_timeout 0; # 类似于关闭长连接
keepalive_timeout 65; # 65s 没有活动则断开连接

2.3 基于IP的访问控制

https://nginx.org/en/docs/http/ngx_http_access_module.html
#允许配置语法
Syntax: allow address | CIDR | unix: | all;
Default:Context: http, server, location, limit_except

#拒绝配置语法
Syntax: deny address | CIDR | unix: | all;
Default:Context: http, server, location, limit_except

#配置案例1:拒绝windwos访问www域名
[root@web01 ~]# cat /etc/nginx/conf.d/01-www.conf 
server   {
    listen       80;
    server_name  www.oldboy.com;
    location / {
        root   /usr/share/nginx/html/www;
        index  index.html index.htm;
        deny 10.0.1.1;
        allow all;
    }
}

windows访问测试403:

img

使用curl访问测试ok:
[root@web01 ~]# curl www.oldzhang.com
www

#配置案例2:只允许windows访问,其他全部拒绝
[root@web01 ~]# cat /etc/nginx/conf.d/01-www.conf    
server   {
    listen       80;
    server_name  www.oldboy.com;
    location / {
        root   /usr/share/nginx/html/www;
        index  index.html index.htm;
        allow 10.0.1.1;
        deny all;
    }
}

windows访问测试ok

img

curl访问测试403:
[root@web01 ~]# curl www.oldzhang.com             
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.0</center>
</body>
</html>

2.4 基于用户认证的访问控制

 配置语法
#访问提示字符串
Syntax: auth_basic string| off;
Default: auth_basic off;
Context: http, server, location, limit_except

#账户密码文件
Syntax: auth_basic_user_file file;
Default: -
Context: http, server, location, limit_except

配置文件:
#1.需要安装 httpd-tools,该包中携带了 htpasswd 命令
[root@web01 ~]# yum install httpd-tools -y
#2.创建新的密码文件, -c 创建新文件 -b 允许命令行输入密码
[root@web01 ~]# htpasswd -b -c /etc/nginx/auth_conf oldzhang oldzhang
Adding password for user oldzhang
#3.nginx 配置调用
[root@web01 ~]# cat /etc/nginx/conf.d/01-www.conf 
server   {
    listen       80;
    server_name  www.oldboy.com;
    location / {
        auth_basic "Auth access Blog Input your Passwd!";
        auth_basic_user_file auth_conf;
        root   /usr/share/nginx/html/www;
        index  index.html index.htm;
    }
}

2.5 请求限制

配置语法:
#模块名 ngx_http_limit_req_module
Syntax: limit_req_zone key zone=name:size rate=rate;
Default: —
Context: http
    
#引用限速模块
Syntax: limit_conn zone number [burst=number] [nodelay];
Default: —
Context: http, server, location

配置文件:
http {
      limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
}
[root@web01 ~]# cat /etc/nginx/conf.d/01-www.conf 
server   {
    listen       80;
    server_name  www.mysun.com;
    limit_req zone=req_zone burst=3 nodelay;
    access_log  /var/log/nginx/www.access.log  main;
    location / {
        root   /html/code/www;
        index  index.html index.htm;
    }
}

为什么限制请求的效果更好?
	我们先来回顾一下 http 协议的连接与请求,首先 HTTP 是建立在 TCP 基础之上, 在完成 HTTP 请求需要先建立TCP 三次握手(称为 TCP 连接) ,在连接的基础上在完成 HTTP 的请求。所以多个 HTTP 请求可以建立在一次 TCP 连接之上, 那么我们对请求的精度限制,当然比对一个连接的限制会更加的有效,因为同一时刻只允许一个 TCP 连接进入, 但是同一时刻多个 HTTP 请求可以通过一个 TCP 连接进入。所以针对 HTTP 的请求限制才是比较优的解决方案。

2.6 location匹配

使用 Nginx Location 可以控制访问网站的路径, 但一个 server 可以有多个 location 配置, 多个 location 的优先级该如何区分

1. location语法介绍

location [=|^~|~|~*|!~|!~*|/] /uri/ { ...
}

2. location语法优先级

img

5.3 配置location匹配规则实战

[root@web01 ~]# cat /etc/nginx/conf.d/location.conf 
server {
    listen       80;
    server_name  www.mysun.com;
    root   /usr/share/nginx/html/www;
    location / {
       return 200  "location / \n";
    }
    location = / {
        return 200 "location = \n";
    }

    location /documents/ {
        return 200 "location /documents/ \n";
    }
    location ^~ /images {
        return 200 "location ^~ /images/ \n";

    }
    location ~* \.(gif|jpg|jpeg)$ {
        return 200 "location ~* \.(gif|jpg|jpeg) \n";
    }
    access_log off;
}

5.4 测试location匹配规则

#精确匹配=/
[root@web01 ~]# curl www.mysun.com
location = 
#没有满足的请求,所以匹配了/
[root@web01 ~]# curl www.mysun.com/oldzhang.html
location / 
#匹配了/documents
[root@web01 ~]# curl www.mysun.com/documents/oldboy.html
location /documents/ 
#没有满足的条件,匹配/
[root@web01 ~]# curl www.mysun.com/oldboy/documents/oldboy.html
location / 
#正则匹配了文件名
[root@web01 ~]# curl www.mysun.com/oldboy.jpg
location ~* \.(gif|jpg|jpeg) 
#~*匹配正则不区分大小写优先于/documents
[root@web01 ~]# curl www.mysun.com/documents/oldboy.jpg
location ~* \.(gif|jpg|jpeg) 
#^~优先匹配于~*
[root@web01 ~]# curl www.mysun.com/images/oldboy.jpg   
location ^~ /images/ 

第三章 制作内网YUM仓库

3.1.为什么需要私有YUM仓库

1.下载速度慢
2.需要有外网
3.有些Base源和epel源软件没有,需要单独创建下载源

3.2.需要的软件

createrepo 
nginx

3.3.配置nginx索引模块

cat >/etc/nginx/conf.d/index.conf <<EOF
server {
    listen       80;
    server_name  yum.repo.com;
    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        autoindex_format html;
        charset utf-8,gbk;
        root   /data/yum;
        index  index.html index.htm;
    }
}
EOF

3.4.安装createrepo

yum install createrepo -y

3.5.准备软件仓库目录并下载需要的软件

yum install --downloadonly --downloaddir=/data/yum nginx screen vim tree -y

3.6.生成yum元数据

createrepo /data/yum 

3.7.客户端生成本地源

cat >/etc/yum.repos.d/local.repo <<EOF
[local]
name=local
enable=1
gpgcheck=0
baseurl=http://10.0.1.6

3.8.客户端测试安装

yum makecache
yum search nginx 
yum install nginx

3.9.更新软件包的操作步骤:

第一种方法:真实下载

1.打开yum缓存

[root@web01 /data/yum]# grep "keepcache" /etc/yum.conf 
keepcache=1

2.清空原来的缓存

yum clean all 

3.下载软件

yum remove php-mysql-5.4 php php-fpm php-common
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
yum install php71w php71w-cli php71w-common php71w-devel php71w-embedded php71w-gd php71w-mcrypt php71w-mbstring php71w-pdo php71w-xml php71w-fpm php71w-mysqlnd php71w-opcache -y

4.移动已经缓存下来的rpm包到yum仓库目录

find /var/cache/yum/ -type f -name "*.rpm"|xargs mv -t /data/yum/

5.生成新的yum元数据

createrepo --update /data/yum/

第二种方法:只下载不安装

yum install --downloadonly --downloaddir=/data/yum php71w php71w-cli php71w-common php71w-devel php71w-embedded php71w-gd php71w-mcrypt php71w-mbstring php71w-pdo php71w-xml php71w-fpm php71w-mysqlnd php71w-opcache 

第四章 LNMP架构概述

4.1 什么是LNMP

LNMP 是一套技术的组合, L=Linux、 N=Nginx、 M=MySQL、 P=PHP

4.2 LNMP架构是如何工作的

首先 Nginx 服务是不能处理动态请求,那么当用户发起动态请求时, Nginx 又是如何进行处理的。
当用户发起 http 请求,请求会被 Nginx 处理,如果是静态资源请求 Nginx 则直接返回,如果是动态请求 Nginx 则通过 fastcgi 协议转交给后端的 PHP 程序处理,具体如下图所示

4.3 Nginx与Fast-CGI工作流程

1.用户通过 http 协议发起请求,请求会先抵达 LNMP 架构中的 Nginx
2.Nginx 会根据用户的请求进行判断,这个判断是有 Location 进行完成
3.判断用户请求的是静态页面, Nginx 直接进行处理
4.判断用户请求的是动态页面, Nginx 会将该请求交给 fastcgi 协议下发
5.fastgi 会将请求交给 php-fpm 管理进程, php-fpm 管理进程接收到后会调用具体的工作进程 warrap
6.warrap 进程会调用 php 程序进行解析,如果只是解析代码 php 直接返回
7.如果有查询数据库操作,则由 php 连接数据库(用户 密码 IP)发起查询的操作
8.最终数据由 mysql->php->php-fpm->fastcgi->nginx->http->user

第五章 LNMP安装部署

5.1 创建www统一用户

[root@web01 ~]# groupadd www -g 666
[root@web01 ~]# useradd www -s /sbin/nologin -M -u 666 -g 666
[root@web01 ~]# id www
uid=666(www) gid=666(www) 组=666(www)

5.2 使用官方仓库安装nginx

[root@web01 ~]# cat /etc/yum.repos.d/nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key

[root@web01 ~]# yum install nginx -y

5.3启动Nginx

[root@web01 ~]# systemctl start nginx
[root@web01 ~]# systemctl enable nginx

5.4 使用第三方拓展源安装php7.1

[root@web01 ~]# yum remove php-mysql-5.4 php php-fpm php-common
[root@web01 ~]# rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
[root@web01 ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
[root@web01 ~]# yum -y install php71w php71w-cli php71w-common php71w-devel php71w-embedded php71w-gd php71w-mcrypt php71w-mbstring php71w-pdo php71w-xml php71w-fpm php71w-mysqlnd php71w-opcache php71w-pecl-memcached php71w-pecl-redis php71w-pecl-mongodb 

5.5 配置php-fpm用户与nginx用户保持一致

[root@web01 ~]# sed -i '/^user/c user = www' /etc/php-fpm.d/www.conf
[root@web01 ~]# sed -i '/^group/c group = www' /etc/php-fpm.d/www.conf

5.6 启动php-fpm并加入开机自启动

[root@web01 ~]# systemctl start php-fpm
[root@web01 ~]# systemctl enable php-fpm

5.7 安装Mariadb数据库

[root@web01 ~]# yum install mariadb-server mariadb -y

5.8 启动Mariadb数据库并加入开机自启动

[root@web01 ~]# systemctl start mariadb
[root@web01 ~]# systemctl enable mariadb

5.9 配置Mariadb账号密码

[root@web01 ~]# mysqladmin password 'oldboy123'
[root@web01 ~]# mysql -uroot -poldboy123

第六章 LNMP环境配置

6.1 Fastcgi语法

设置 fastcgi 服务器的地址,该地址可以指定为域名或 IP 地址,以及端口

Syntax: fastcgi_pass address;
Default:Context: location, if in location

#语法示例
fastcgi_pass localhost:9000;
fastcgi_pass unix:/tmp/fastcgi.socket;

设置 fastcgi 默认的首页文件,需要结合 fastcgi_param 一起设置

Syntax: fastcgi_index name;
Default:Context: http, server, location

通过 fastcgi_param 设置变量,并将设置的变量传递到后端的 fastcgi 服务器

Syntax: fastcgi_param parameter value [if_not_empty];
Default:Context: http, server, location

#语法示例
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /code$fastcgi_script_name;

6.2 最终Nginx连接FastCGI服务器配置如下

[root@web01 ~]# cat /etc/nginx/conf.d/php.conf
server {
    server_name www.mysun.com;
    listen 80;
    root /code;
    index index.php index.html;

    location ~ \.php$ {
        root /code;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

6.3 在/code目录下创建info.php文件并访问测试

[root@web01 ~]# mkdir /code
[root@web01 ~]# chown -R www:www /code/
[root@web01 ~]# cat /code/info.php
<?php
    phpinfo();
?>

6.4 检查nginx语法并重启

[root@web01 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 ~]# systemctl restart nginx

6.5 绑定hosts然后在浏览器访问

http://www.oldboy.com/info.php

6.6 测试php和数据库访问是否正常

[root@web01 ~]# cat /code/mysql.php 
<?php
    $servername = "localhost";
    $username = "root";
    $password = "oldboy123";

    // 创建连接
    $conn = mysqli_connect($servername, $username, $password);

    // // 检测连接
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "php 连接 MySQL 数据库成功";
?>

6.7 通过浏览器访问数据库页面

第七章 部署博客Wordpress

7.1 配置Nginx虚拟主机站点

[root@web01 ~]# cat /etc/nginx/conf.d/wordpress.conf    
server {
    listen 80;
    server_name blog.oldboy.com;
    root /code/wordpress;
    index index.php index.html;

    location ~ \.php$ {
        root /code/wordpress;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

7.2 重启nginx

[root@web01 ~]# systemctl restart nginx

7.3 下载解压wordpress到代码目录

[root@web01 ~]# mkdir /code
[root@web01 ~]# cd /code/
[root@web01 /code]# wget https://cn.wordpress.org/wordpress-4.9.4-zh_CN.tar.gz
[root@web01 /code]# tar xf wordpress-4.9.4-zh_CN.tar.gz 
[root@web01 /code]# chown -R www:www /code/wordpress

7.4 创建wordpress数据库

[root@web01 /code]# mysql -uroot -poldboy123
> create database wordpress;
> exit

7.5 浏览器访问wordpress并部署







第八章 部署问答网站Wecenter

8.1 配置Nginx虚拟站点

[root@web01 ~]# cat /etc/nginx/conf.d/wecenter.conf 
server {
    listen 80;
    server_name zh.oldboy.com;
    root /code/wecenter;
    index index.php index.html;

    location ~ \.php$ {
        root /code/wecenter;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

8.2 下载解压wecenter并授权

[root@web01 ~]# mkdir /code/zh -p
[root@web01 ~]# cd /opt/
[root@web01 /opt]# rz
[root@web01 /opt]# ls
WeCenter_3-3-2.zip
[root@web01 /opt]# unzip WeCenter_3-3-2.zip -d /code/zh/
[root@web01 /opt]# chown -R www:www /code/

8.3 创建wecenter数据库

[root@web01 ~]# mysql -uroot -poldboy123
> create database zh;
> exit;

8.4 浏览器访问




5.5 清除首页安装文件

[root@web01 ~]# rm -rf /code/zh/install

第九章 拆分数据库

9.1 为什么要进行数据库的拆分

由于单台服务器运行 LNMP 架构会导致网站访问缓慢,当内存被吃满时,很容易导致系统出现 oom,从而 kill 掉MySQL 数据库,所以需要将 web 和数据库进行独立部署

9.2 数据库拆分后解决了什么问题

1.缓解 web 网站的压力
2.增强数据库读写性能
3.提高用户访问的速度

9.3 数据库拆分架构演变过程

9.4 数据库拆分环境搭建

web01 172.16.1.7    nginx+php
db01  172.16.1.51   mysql

9.5 数据库拆分详细步骤

1 web01上备份数据库并拷贝到db01上

备份 web01 上的数据库,oldboy123 是数据库密码

[root@web01 ~]# mysqldump -uroot -p'oldboy123' -A --single-transaction > mysql-all.sql
[root@web01 ~]# mysqldump -uroot -poldboy123 -B wordpress zhihu >/backup/web.sql

将 web01 上备份的数据库拷贝至 db01 服务器上

[root@web01 ~]# scp mysql-all.sql 10.0.1.51:/tmp

2 db01恢复数据库

将 web01 服务器上推送的数据库备份文件恢复至 db01 服务器新数据库中

注意:在导入数据库之前,一定要先备份这台服务器上的数据。因为导入数据库备份的sql文件会默认先删除本地同名的库!!!

[root@db01 ~]# yum install mariadb mariadb-server -y
[root@db01 ~]# systemctl start mariadb
[root@db01 ~]# systemctl enable mariadb
[root@db01 ~]# mysqladmin password 'oldboy123'
[root@db01 ~]# mysql -uroot -p'oldboy123' < /tmp/mysql-all.sql
[root@db01 ~]# mysql -uroot -p'oldboy123' -e "show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| wordpress          |
| zh                 |
+--------------------+

3 db01数据库进行授权

在新数据库上授权, 允许所有网段, 通过 all 账户连接并操作该数据库
授权所有权限 grant all privileges
授权所有库所有表 *.*
将授权赋予给哪个用户,这个用户只能通过哪个网段过来(%所有) 'all'@'%'
授权该用户登录的密码 identified by
[root@db01 ~]# mysql -uroot -p'oldboy123'
> grant all privileges on *.* to 'all'@'%' identified by 'oldboy123';
> flush privileges; 
>exit;

grant all privileges on wordpress.* to 'web'@'172.16.1.%' identified by 'oldboy123';
grant all privileges on zhihu.* to 'web'@'172.16.1.%' identified by 'oldboy123';

测试使用IP地址能不能登陆

[root@db01 ~]# mysql -uall -p'oldboy123' -h 10.0.1.51
> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| wordpress          |
| zh                 |
+--------------------+

4 web01修改代码连接到新数据库

修改wordpress

[root@web01 ~]# vim /code/wordpress/wp-config.php
/** MySQL数据库用户名 */
define('DB_USER', 'all');

/** MySQL数据库密码 */
define('DB_PASSWORD', 'oldboy123');

/** MySQL主机 */
define('DB_HOST', '172.16.1.51');

修改wecenter

[root@web01 ~]# vim /code/zh/system/config/database.php
  'host' => '172.16.1.51',
  'username' => 'all',
  'password' => 'oldboy123',
  'dbname' => 'zh',

停止web01上的数据库

[root@web01 ~]# systemctl stop mariadb.service 
[root@web01 ~]# systemctl disable mariadb.service 

5 测试访问

此时如果打开网页没有问题则表明数据库拆分完成

第十章 拓展WEB服务器

10.1 为什么要拓展多台web节点

单台 web 服务器能抗住的访问量是有限的,配置多台 web 服务器能提升更高的访问速度

10.2 拓展多台web解决了什么问题

1.单台 web 节点如果故障,会导致业务 down 机
2.多台 web 节点能保证业务的持续稳定,扩展性高
3.多台 web 节点能有效的提升用户访问网站的速度

10.3 多台web服务器架构组成

10.4 多台web服务器思路

1.可以使用ansible批量部署多台web服务器
2.配置内网私有yum仓库
3 按照web01的步骤安装好nginx和php,然后远程拷贝代码到新机器

10.5 正常配置步骤

1 创建用户名密码

[root@web02 ~]# groupadd www -g 666
[root@web02 ~]# useradd www -s /sbin/nologin -M -u 666 -g 666

2 安装NP

可以直接从web01上拷贝yum源到本机yum目录

[root@web02 ~]# scp -rp root@172.16.1.7:/etc/yum.repos.d/* /etc/yum.repos.d/
[root@web02 ~]# scp -rp root@172.16.1.7:/etc/pki/rpm-gpg/* /etc/pki/rpm-gpg/
[root@web02 ~]# yum install nginx -y
[root@web02 ~]# yum -y install php71w php71w-cli php71w-common php71w-devel php71w-embedded php71w-gd php71w-mcrypt php71w-mbstring php71w-pdo php71w-xml php71w-fpm php71w-mysqlnd php71w-opcache php71w-pecl-memcached php71w-pecl-redis php71w-pecl-mongodb 

3 拷贝web01的nginx配置文件到web02

[root@web02 ~]# scp -rp root@172.16.1.7:/etc/nginx /etc/

4 拷贝web01的php配置文件到web02

[root@web02 ~]# scp -rp root@172.16.1.7:/etc/php-fpm.d /etc/

5 拷贝代码目录到web02

[root@web01 ~]# tar czf code.tar.gz /code
[root@web01 ~]# scp code.tar.gz root@172.16.1.8:/tmp

6 web02上将代码解压到相应目录

[root@web02 ~]# tar zxf /tmp/code.tar.gz -C /

7 web02上启动nginx和php-fpm并加入开机自启动

[root@web02 ~]# systemctl start nginx php-fpm
[root@web02 ~]# systemctl enable nginx php-fpm 

8 web访问测试

修改hosts为web02的地址,然后浏览器访问测试

第十一章 将静态资源挂载到共享存储

11.1 为什么要拆分静态资源到独立服务器

当后端的 web 节点出现多台时,会导致用户上传的图片、视频附件等内容仅上传至一台 web 服务器,那么其他的web 服务器则无法访问到该图片

11.2 新增一台nfs存储解决了什么问题

1.保证了多台 web 节点静态资源一致。
2.有效节省多台 web 节点的存储空间。
3.统一管理静态资源,便于后期推送至 CDN 进行静态资源加速

11.3 多台web节点架构组成

11.4 多台web节点环境规划

web01      nginx+php
web02      nginx+php
db01        mysql
nfs           nfs

11.5 共享存储配置

1 安装配置NFS

[root@nfs01 ~]# yum install nfs-utils -y
[root@nfs01 ~]# cat /etc/exports
/data/blog 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)
/data/zh 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)

2 创建共享目录并进行授权

[root@nfs01 ~]# mkdir /data/{blog,zh} -p
[root@nfs01 ~]# chown -R www.www /data

3 启动nfs服务并加入开机自启

[root@nfs01 ~]# systemctl restart nfs-server

11.6 web01端操作步骤如下

1 web01节点挂在nfs

[root@web01 ~]# yum install nfs-utils -y
[root@web01 ~]# showmount -e 172.16.1.31
Export list for 172.16.1.31:
/data/zh   172.16.1.0/24
/data/blog 172.16.1.0/24

2 查找Wordpress 静态资源存放的位置

在wordpress的文章里添加一张图片,然后查看图片URL资源

这里地址为:
http://blog.oldboy.com/wp-content/uploads/2019/07/DNS图.png

3 备份web01服务器上Wordpress 的静态资源

[root@web01 ~]# cd /code/wordpress/wp-content
[root@web01 /code/wordpress/wp-content]# cp -a uploads/ uploads_bak/

4 web01客户端执行挂载操作

[root@web01 /code/wordpress/wp-content]# mount -t nfs 172.16.1.31:/data/blog /code/wordpress/wp-content/uploads/
[root@web01 /code/wordpress/wp-content]# cp -rp uploads_bak/* uploads/

5 将挂载信息加入开机自启

[root@web01 ~]# tail -1 /etc/fstab 
172.16.1.31:/data/blog /code/wordpress/wp-content/uploads nfs defaults 0 0

11.7 web02端操作

web02端操作和web01端一样

[root@web02 ~]# cd /code/wordpress/wp-content
[root@web02 /code/wordpress/wp-content]# cp -a uploads/ uploads_bak/
[root@web02 /code/wordpress/wp-content]# mount -t nfs 172.16.1.31:/data/blog /code/wordpress/wp-content/uploads/
[root@web02 /code/wordpress/wp-content]# cp -rp uploads_bak/* uploads/
[root@web02 ~]# tail -1 /etc/fstab 
172.16.1.31:/data/blog /code/wordpress/wp-content/uploads nfs defaults 0 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值