Nginx的部署与配置

Nginx

简介

Nginx是一款自由的、开源的、高性能的HTTP服务器和 反向代理 服务器;同时也是一个IMAP、POP3、SMTP代理服务器;Nginx可以作为一个HTTP服务器进行网站的发布处理,另外Nginx可以作为反向代理进行负载均衡的实现。

Nginx使用基于事件驱动架构,使得其可以支持数以百万级别的TCP连接
高度的模块化和自由软件许可证使得第三方模块层出不穷(开源)
Nginx是一个跨平台服务器,可以运行在Linux,Windows,FreeBSD,Solaris,AIX,Mac OS等操作系统上

Nginx的特点

  • 更快:

    • 单次请求会得到更快的响应。
    • 在高并发环境下,Nginx 比其他 WEB 服务器有更快的响应。
  • 高扩展性:

    • Nginx 是基于模块化设计,由多个耦合度极低的模块组成,因此具有很高的扩展性。许多 高流量的网站都倾向于开发符合自己业务特性的定制模块。
  • 高可靠性:

    • Nginx 的可靠性来自于其核心框架代码的优秀设计,模块设计的简单性。另外,官方提供的常用模块都非常稳定,每个 worker 进程相对独立,master 进程在一个 worker 进程出错时可以快速拉起新的 worker 子进程提供服务。
  • 低内存消耗:

    • 一般情况下,10000个非活跃的 HTTP Keep-Alive 连接在 Nginx 中仅消耗 2.5MB 的内存,这是 Nginx 支持高并发连接的基础。
      单机支持10万以上的并发连接:理论上,Nginx 支持的并发连接上限取决于内存,10万远未封顶。
  • 热部署:

    • master 进程与 worker 进程的分离设计,使得 Nginx 能够提供热部署功能,即在 7x24 小时不间断服务的前提下,升级 Nginx 的可执行文件。当然,它也支持不停止服务就更新配置项,更换日志文件等功能。
  • 最自由的 BSD 许可协议:

    • 这是 Nginx 可以快速发展的强大动力。BSD 许可协议不只是允许用户免费使用 Nginx ,它还允许用户在自己的项目中直接使用或修改 Nginx 源码,然后发布。
  • 稳定性极高

    • Nginx 解决高并发
    • Nginx高并发原理( 多进程+epoll实现高并发 )
    • Nginx 在启动后,会有一个 master 进程和多个相互独立的 worker 进程。
    • 每个子进程只有一个线程(协程),采用的 IO多路复用模型epoll,实现高并发。
  • epoll能实现高并发原理

    • epoll() 中内核则维护一个链表,epoll_wait 方法可以获取到链表长度,不为0就知道文件描述符准备好了。
    • 在内核实现中 epoll 是根据每个 sockfd 上面的与设备驱动程序建立起来的回调函数实现的。
    • 某个 sockfd 上的事件发生时,与它对应的回调函数就会被调用,来把这个 sockfd 加入链表,其他处于“空闲的”状态的则不会。
    • epoll上面链表中获取文件描述,这里使用内存映射(mmap)技术, 避免了复制大量文件描述符带来的开销
    • 内存映射(mmap):内存映射文件,是由一个文件到一块内存的映射,将不必再对文件执行I/O操作

nginx和apache比较

nginx相对于apache的优点

  • 轻量级,同样起web 服务,比apache 占用更少的内存及资源
  • 抗并发,nginx 处理请求是异步非阻塞的,而apache 则是阻塞型的,在高并发下nginx 能保持低资源低消耗高性能
  • 高度模块化的设计,编写模块相对简单,社区活跃,各种高性能模块出品迅速啊

apache 相对于nginx 的优点

  • apache 更为成熟,少 bug ,稳定性好
  • rewrite ,比nginx 的rewrite 强大
  • 模块超多,基本想到的都可以找到

Nginx的工作原理

Nginx由内核和模块组成。

Nginx本身做的工作实际很少,当它接到一个HTTP请求时,它仅仅是通过查找配置文件将此次请求映射到一个location block,而此location中所配置的各个指令则会启动不同的模块去完成工作,因此模块可以看做Nginx真正的劳动工作者。通常一个location中的指令会涉及一个handler模块和多个filter模块(当然,多个location可以复用同一个模块)。handler模块负责处理请求,完成响应内容的生成,而filter模块对响应内容进行处理。

用户根据自己的需要开发的模块都属于第三方模块。正是有了这么多模块的支撑,Nginx的功能才会如此强大。

Nginx的模块从结构上分为核心模块、基础模块和第三方模块:

  • 核心模块:HTTP模块、EVENT模块和MAIL模块
  • 基础模块:HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块,
  • 第三方模块:HTTP Upstream Request Hash模块、Notice模块和HTTP Access Key模块。

Nginx的模块从功能上分为如下三类:

  • Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。Handlers处理器模块一般只能有一个。
  • Filters (过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由Nginx输出。
  • Proxies (代理类模块)。此类模块是Nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如FastCGI等进行交互,实现服务代理和负载均衡等功能。

常规的HTTP请求和响应的过程

Nginx进程模型

Nginx默认采用多进程工作方式,Nginx启动后,会运行一个master进程和多个worker进程。其中master充当整个进程组与用户的交互接口,同时对进程进行监护,管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。worker用来处理基本的网络事件,worker之间是平等的,他们共同竞争来处理来自客户端的请求。

nginx的进程模型如图所示:
进程图
在创建master进程时,先建立需要监听的socket(listenfd),然后从master进程中fork()出多个worker进程,如此一来每个worker进程多可以监听用户请求的socket。一般来说,当一个连接进来后,所有在Worker都会收到通知,但是只有一个进程可以接受这个连接请求,其它的都失败,这是所谓的惊群现象。nginx提供了一个accept_mutex(互斥锁),有了这把锁之后,同一时刻,就只会有一个进程在accpet连接,这样就不会有惊群问题了。

先打开accept_mutex选项,只有获得了accept_mutex的进程才会去添加accept事件。nginx使用一个叫ngx_accept_disabled的变量来控制是否去竞争accept_mutex锁。ngx_accept_disabled = nginx单进程的所有连接总数 / 8 -空闲连接数量,当ngx_accept_disabled大于0时,不会去尝试获取accept_mutex锁,ngx_accept_disable越大,于是让出的机会就越多,这样其它进程获取锁的机会也就越大。不去accept,每个worker进程的连接数就控制下来了,其它进程的连接池就会得到利用,这样,nginx就控制了多进程间连接的平衡。

每个worker进程都有一个独立的连接池,连接池的大小是worker_connections。这里的连接池里面保存的其实不是真实的连接,它只是一个worker_connections大小的一个ngx_connection_t结构的数组。并且,nginx会通过一个链表free_connections来保存所有的空闲ngx_connection_t,每次获取一个连接时,就从空闲连接链表中获取一个,用完后,再放回空闲连接链表里面。一个nginx能建立的最大连接数,应该是worker_connections * worker_processes。当然,这里说的是最大连接数,对于HTTP请求本地资源来说,能够支持的最大并发数量是worker_connections * worker_processes,而如果是HTTP作为反向代理来说,最大并发数量应该是worker_connections * worker_processes/2。因为作为反向代理服务器,每个并发会建立与客户端的连接和与后端服务的连接,会占用两个连接。

Nginx处理HTTP请求流程

http请求是典型的请求-响应类型的的网络协议。http是文件协议,所以我们在分析请求行与请求头,以及输出响应行与响应头,往往是一行一行的进行处理。通常在一个连接建立好后,读取一行数据,分析出请求行中包含的method、uri、http_version信息。然后再一行一行处理请求头,并根据请求method与请求头的信息来决定是否有请求体以及请求体的长度,然后再去读取请求体。得到请求后,我们处理请求产生需要输出的数据,然后再生成响应行,响应头以及响应体。在将响应发送给客户端之后,一个完整的请求就处理完了。

处理流程图:
在这里插入图片描述

网页访问流程

利用DNS协议进行域名解析 --> 建立tcp协议三次握手过程 --> 客户端发出访问网站相应页面请求(发出http协议请求报文) --> 服务端发出相应访问页面的请求信息(发出http) --> 断开tcp协议四次挥手过程

Nginx的应用环境

Nginx 代理

说到代理,首先我们要明确一个概念,所谓代理就是一个代表、一个渠道此时就涉及到两个角色,一个是被代理角色 (A_),一个是目标角色 (B_),A_ 通过这个代理访问 B_ 完成一些任务的过程称为代理 (C_) 操作过程;比如客人去买双鞋,这个店铺就是 (C_),(A_) 就是厂家,(B_) 就是用户。代理呢又分为正向代理和反向代理

  • 反向代理
    反向代理应该是Nginx做的最多的一件事了,什么是反向代理呢,以下是百度百科的说法:反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。简单来说就是真实的服务器不能直接被外部网络访问,所以需要一台代理服务器,而代理服务器能被外部网络访问的同时又跟真实服务器在同一个网络环境,当然也可能是同一台服务器,端口不同而已。

    如下图:
    在这里插入图片描述

  • 负载均衡
    负载均衡也是Nginx常用的一个功能,简单而言就是当有2台或2台以上服务器时,根据规则随机的将请求分发到指定的服务器上处理,负载均衡配置一般都需要同时配置反向代理,通过反向代理跳转到负载均衡。而Nginx目前支持自带3种负载均衡策略,还有2种常用的第三方策略

    如下图:在这里插入图片描述

  • WEB服务器
    Nginx本身也是一个静态资源的服务器,当只有静态资源的时候,就可以使用Nginx来做服务器,同时现在也很流行动静分离,就可以通过Nginx来实现,首先看看Nginx做静态资源服务器

  • 静态分离
    动静分离是让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作,这就是网站静态化处理的核心思路。

    如下图:
    在这里插入图片描述

Nginx的安装

# 关闭防火墙
[root@master ~]# systemctl disable --now firewalld
[root@master ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@master ~]# setenforce 0

# 创建系统用户nginx
[root@master ~]# useradd  -r -M -s /sbin/nologin nginx

# 安装依赖包
[root@master ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@master ~]# yum -y groups mark install 'Development Tools'

# 创建日志存放目录
[root@master ~]# mkdir -p /var/log/nginx
[root@master ~]# chown -R nginx.nginx /var/log/nginx

# 下载nginx包
[root@master ~]# cd /usr/src/
[root@master src]# wget http://nginx.org/download/nginx-1.20.0.tar.gz

# 编译安装
[root@master src]# tar xf nginx-1.20.0.tar.gz
[root@master src]# cd nginx-1.20.0
[root@master nginx-1.20.0]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log

[root@master nginx-1.20.0]# make && make install

# 配置环境变量
[root@master ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@master ~]# source /etc/profile.d/nginx.sh

# 启动nginx
[root@master ~]# nginx
[root@master ~]# ss -antl
State      Recv-Q     Send-Q          Local Address:Port           Peer Address:Port     
LISTEN     0          128                   0.0.0.0:80                  0.0.0.0:*        
LISTEN     0          128                   0.0.0.0:22                  0.0.0.0:*        
LISTEN     0          128                      [::]:22                     [::]:*    

配置service文件

[root@master ~]# cat /usr/lib/systemd/system/nginx.service 
[Unit]
Description=nginx-The High-performance HTTP Server              
After=network.target remote-fs.target nss-lookup.target         

[Service]
Type=forking            
PIDFile=/usr/local/nginx/logs/nginx.pid 
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf 
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf       
ExecReload=/usr/local/nginx/sbin/nginx -s reload        
ExecStop=/usr/local/nginx/sbin/nginx -s stop                
ExecQuit=/usr/local/nginx/sbin/nginx -s quit                
PrivateTmp=true         

[Install]
WantedBy=multi-user.target      

systemctl daemon-reload
systemctl start nginx.service
服务控制方式
使用nginx命令
-t  //检查配置文件语法
-v  //输出nginx的版本
-c  //指定配置文件的路径
-s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}

如:修改nginxd默认80端口为8080
修改前

[root@master conf]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port            
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:80                       0.0.0.0:*        
LISTEN        0             128                           [::]:22                          [::]:*        
[root@master conf]vim /usr/local/nginx/conf/nginx.conf
 34 
 35     server {
 36         listen       8080;
 37         server_name  localhost;
 38 

[root@master conf]# nginx -t  //检查语法
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

//修改后,端口改为8080
[root@master conf]# nginx -s stop;nginx
[root@master conf]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*             
LISTEN        0             128                           [::]:22                          [::]:*       

访问测试
在这里插入图片描述

Nginx的配置文件详解

主配置文件:/usr/local/nginx/conf/nginx.conf

  • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
  • 可以在启动nginx时通过-c选项来指定要读取的配置文件

nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置
sites.conf配置nginx提供的网站,包括虚拟主机
nginx.conf配置详解

nginx.conf的内容分为以下几段:

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置
  • 配置指令:要以分号结尾,语法格式如下:
derective value1 [value2 ...];

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value
    用于调试、定位问题的配置参数
daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志

error_log里的位置和级别能有以下可选项:

位置级别
file stderr syslog:server=address[,parameter=value] memory:size debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg
正常运行必备的配置参数

user USERNAME [GROUPNAME]; //指定运行worker进程的用户和组

//用法
Syntax:	user user [group];       #语法
Default: user nobody nobody;    #默认值
Context: main                  #可以配置在那个字段中

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;					#建议手动指定用户
worker_processes  1;

pid /path/to/pid_file; //指定nginx守护进程的pid文件

//用法
Syntax:	pid file;
Default: pid logs/nginx.pid;
Context: main

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  1;
error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;     //nginx运行后,此文件中会生成守护进程的pid

worker_rlimit_nofile number; //设置所有worker进程最大可以打开的文件数,默认为1024

//用法
Syntax:	worker_rlimit_nofile number;
Default:	1024
Context:	main

worker_rlimit_core size; //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

//用法
Syntax:	worker_rlimit_core size;
Default:	—
Context:	main

优化性能的配置参数

worker_processes n; //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数

//用法
Syntax:	worker_processes number | auto;
Default: worker_processes 1;
Context: main

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  4;    //修改nginx的worker进程数量,默认为1

[root@master ~]# nginx -s reload    //发送服务控制信号,重启,重载配置文件
[root@master ~]# ps -ef | grep nginx
root       46016       1  0 19:18 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx      46017   46016  0 19:18 ?        00:00:00 nginx: worker process
nginx      46018   46016  0 19:18 ?        00:00:00 nginx: worker process
nginx      46019   46016  0 19:18 ?        00:00:00 nginx: worker process
nginx      46020   46016  0 19:18 ?        00:00:00 nginx: worker process
root       46220    1602  0 19:18 pts/0    00:00:00 grep --color=auto nginx

注: worker_processes的数量*worker_connections的数量=nginx所能支持的最大并发连接数量,在实际情况最大并发数建议不超过30000

worker_cpu_affinity cpumask …; //将进程绑定到某cpu中,避免频繁刷新缓存

//用法
Syntax:	worker_cpu_affinity cpumask ...;
        worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main


##TOP进程管理
worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心

#查看cpu核心数
[root@master ~]# nproc
2
#修改nginx.conf配置文件,将进程绑定在0.1的进程上
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;
worker_cpu_affinity 0001 0010;
[root@master ~]# systemctl restart nginx
[root@master ~]# ps -ef | grep nginx
root       14105       1  0 19:00 ?        00:00:00 nginx: master process nginx
nginx      14106   14105  0 19:00 ?        00:00:00 nginx: worker process
nginx      14107   14105  0 19:00 ?        00:00:00 nginx: worker process
root       30991    1602  0 19:10 pts/0    00:00:00 grep --color=auto nginx


[root@master ~]# top
Fields Management for window 1:Def, whose current sort field is %CPU
   Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
top - 19:08:21 up 15 min,  2 users,  load average: 0.27, 0.31, 0.23
Tasks: 219 total,   2 running, 217 sleeping,   0 stopped,   0 zombie
%Cpu(s):  3.9 us,  6.5 sy,  0.0 ni, 88.4 id,  0.0 wa,  0.7 hi,  0.5 si,  0.0 st
MiB Mem :   1800.6 total,   1274.6 free,    230.2 used,    295.8 buff/cache
MiB Swap:   2092.0 total,   2092.0 free,      0.0 used.   1413.0 avail Mem 


    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                       
      1 root      20   0  242256  10628   8180 S   0.0   0.3   0:00.92 systemd                                                       
      2 root      20   0       0      0      0 S   0.0   0.0   0:00.00 kthreadd                                                      
      3 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 rcu_gp    
                                                          
#按shift+f ,输入nginx,回车

Locate string nginx

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                       
   1485 root      20   0   26516   4928   3452 S   0.0   0.1   0:00.03 bash                                                          
   1571 root      20   0   80256   1092     56 S   0.0   0.0   0:00.00 nginx                                                         
   1572 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                         
   1573 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                         
   1574 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx   

# 按f, 将光标移到  P       = Last Used Cpu (SMP)
Fields Management for window 1:Def, whose current sort field is %CPU
   Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
   'd' or <Space> toggles display, 's' sets sort.  Use 'q' or <Esc> to end!

* PID     = Process Id             WCHAN   = Sleeping in Function
* USER    = Effective User Name    Flags   = Task Flags <sched.h>
* PR      = Priority               CGROUPS = Control Groups      
* NI      = Nice Value             SUPGIDS = Supp Groups IDs     
* VIRT    = Virtual Image (KiB)    SUPGRPS = Supp Groups Names   
* RES     = Resident Size (KiB)    TGID    = Thread Group Id     
* SHR     = Shared Memory (KiB)    OOMa    = OOMEM Adjustment    
* S       = Process Status         OOMs    = OOMEM Score current 
* %CPU    = CPU Usage              ENVIRON = Environment vars    
* %MEM    = Memory Usage (RES)     vMj     = Major Faults delta  
* TIME+   = CPU Time, hundredths   vMn     = Minor Faults delta  
* COMMAND = Command Name/Line      USED    = Res+Swap Size (KiB) 
  PPID    = Parent Process pid     nsIPC   = IPC namespace Inode 
  UID     = Effective User Id      nsMNT   = MNT namespace Inode 
  RUID    = Real User Id           nsNET   = NET namespace Inode 
  RUSER   = Real User Name         nsPID   = PID namespace Inode 
  SUID    = Saved User Id          nsUSER  = USER namespace Inode
  SUSER   = Saved User Name        nsUTS   = UTS namespace Inode 
  GID     = Group Id               LXC     = LXC container name  
  GROUP   = Group Name             RSan    = RES Anonymous (KiB) 
  PGRP    = Process Group Id       RSfd    = RES File-based (KiB)
  TTY     = Controlling Tty        RSlk    = RES Locked (KiB)    
  TPGID   = Tty Process Grp Id     RSsh    = RES Shared (KiB)    
  SID     = Session Id             CGNAME  = Control Group name  
  nTH     = Number of Threads      NU      = Last Used NUMA node 
  P       = Last Used Cpu (SMP) 
  TIME    = CPU Time            
  SWAP    = Swapped Size (KiB)  
  CODE    = Code Size (KiB)     
  DATA    = Data+Stack (KiB)    
  nMaj    = Major Page Faults   
  nMin    = Minor Page Faults   
  nDRT    = Dirty Pages Count 

##空格选择,按q(退出并查看)

   13117 root      20   0      0      0 I   0.0   0.0   0:00.07 kworker/1:0-events_power_efficient         1 
  14105 root      20   0   1096     60 S   0.0   0.1   0:00.00 nginx                                      1 
  14106 nginx     20   0   6320   4740 S   0.0   0.3   0:00.00 nginx                                      0 
  14107 nginx     20   0   6368   4788 S   0.0   0.3   0:00.01 nginx                                      1 
  14862 root      20   0   1912   1648 S   0.0   0.1   0:00.00 anacron                                    0 
  20824 root      20   0      0      0 I   0.0   0.0   0:00.00 kworker/0:2-cgroup_destroy                 0 
  20825 root      20   0      0      0 I   0.0   0.0   0:00.06 kworker/0:3-events                         0 
  20961 root      20   0      0      0 I   0.0   0.0   0:00.01 kworker/u256:0-events_unbound            

timer_resolution interval; 计时器解析度。降低此值,可减少gettimeofday()系统调用的次数

//用法
Syntax:	timer_resolution interval;
Default: —
Context: main

worker_priority number; 指明worker进程的nice值

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
worker_priority -20;
[root@master ~]# systemctl restart nginx
[root@master ~]# ps -elf |grep nginx
[root@master ~]# ps -elf | grep nginx
1 S root       65708       1  0  80   0 - 20064 -      19:29 ?        00:00:00 nginx: master process nginx
5 S nginx      65709   65708  0  60 -20 - 27927 do_epo 19:29 ?        00:00:00 nginx: worker process
5 S nginx      65710   65708  0  60 -20 - 27927 do_epo 19:29 ?        00:00:00 nginx: worker process
5 S nginx      65711   65708  0  60 -20 - 27927 do_epo 19:29 ?        00:00:00 nginx: worker process
5 S nginx      65712   65708  0  60 -20 - 27927 do_epo 19:29 ?        00:00:00 nginx: worker process
0 S root       65809    1602  0  80   0 -  3086 -      19:29 pts/0    00:00:00 grep --color=auto nginx

事件相关的配置:event{}段中的配置参数

accept_mutex {off|on}; //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求

//用法
Syntax:	accept_mutex on | off;
Default: accept_mutex off;
Context: events

lock_file file; //accept_mutex用到的互斥锁锁文件路径

//用法
Syntax:	lock_file file;
Default: lock_file logs/nginx.lock;
Context: main

use [epoll | rtsig | select | poll]; //指明使用的事件模型,建议让nginx自行选择

//用法
Syntax:	use method;
Default:	—
Context:	events

worker_connections #; //每个进程能够接受的最大连接数

//用法
Syntax:	worker_connections number;
Default: worker_connections 512;
Context: events

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes 3 ;    
worker_cpu_affinity 0001 0010 0100;
worker_priority -20;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  20480;   #最大连接数乘以进程数量除以2就是最大访问并发量3000
}


[root@localhost ~]# ab -n 30000 http://192.168.58.10/index.html
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.58.20 (be patient)
Completed 3000 requests
Completed 6000 requests
Completed 9000 requests
Completed 12000 requests
Completed 15000 requests
Completed 18000 requests
Completed 21000 requests
Completed 24000 requests
Completed 27000 requests
Completed 30000 requests
Finished 30000 requests    //同时处理30000个并发请求


网络连接相关的配置参数

keepalive_timeout number; //长连接的超时时长,默认为65s

//用法
Syntax:	keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 65s;
Context: http, server, location

[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
....
http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
....


keepalive_requests number; //在一个长连接上所能够允许请求的最大资源数

//用法
Syntax:	keepalive_requests number;
Default: keepalive_requests 1000;
Context: http, server, location

....
http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    keepalive_requests 1000;
....


keepalive_disable [msie6|safari|none]; //为指定类型的UserAgent禁用长连接

//用法
Syntax:	keepalive_disable none | browser ...;
Default: keepalive_disable msie6;
Context: http,server,location

tcp_nodelay on|off; //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on

//用法
Syntax:	tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location

client_header_timeout number; //读取http请求报文首部的超时时长

//用法
Syntax:	client_header_timeout time;
Default: client_header_timeout 60s;
Context: http, server

client_body_timeout number; //读取http请求报文body部分的超时时长

//用法
Syntax:	send_timeout time;
Default: send_timeout 60s;
Context: http, server, location

send_timeout number; //发送响应报文的超时时长

//用法
Syntax:	send_timeout time;
Default: send_timeout 60s;
Context: http, server, location

fastcgi的相关配置参数

php要启用fpm模型 应用于 LNMP架构

location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;				#定义反向代理,此处的IP地址应该为PHP服务器的地址
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $DocumentRoot$fastcgi_script_name;
            include        fastcgi_params;
        }
http{}段的配置参数
http{…}段是配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块

http {                               //协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {                         //负载均衡配置
    ...
  }
  server {                           //服务器级别,每个server类似于httpd中的一个<VirtualHost>
    listen 80;
    server_name localhost;
    location / {                     //请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令

server {}:定义一个虚拟主机

......
    server{
        listen       8080;
        server_name  www.xu.com;

        location / {
            root html/test;
            index index.html;
       }
    }
 ......
 
[root@master ~]# cd /usr/local/nginx/html/
[root@master html]# ls
50x.html  index.html
[root@master html]# mkdir test
[root@master html]# ls
50x.html  index.html  test
[root@masterhtml]# echo 'testing' test/index.html
[root@master html]# nginx -s stop;nginx
[root@master html]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                           [::]:22                          [::]:*           

//listen:指定监听的地址和端口
listen address[:port];			
listen port;

//server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符,当存在多个server时,匹配顺序如下:

1. 先做精确匹配检查
2. 左侧通配符匹配检查,如*.example.com
3. 右侧通配符匹配检查,如web.*
4. 正则表达式匹配检查,如~ ^.*\.example\.com$
5. default_server

网页测试(自动读取根目录(html)下的文件)

在这里插入图片描述

location区段

通过指定模式来与客户端请求的URI相匹配

功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
修饰符功能
=精准匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等
没有修饰符

表示必须以指定模式开始

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


server {
        listen       8080;
        server_name  localhost;

location /test {
                echo "This is test!";
        }


[root@master conf]# nginx -s reload

如下内容就可正确匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/test?abc123=a1b2
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/test/
This is test!
精确匹配

=:表示必须与指定的模式精确匹配

[root@master conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location = /test {
                echo "This is test!";
        }

[root@master conf]# nginx -s reload

如下内容就可正确匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/test?abc123=a1b2
This is test!

如下内容则无法匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl http://192.168.58.10:8080/test/test
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

正则表达式模式匹配(区分大小写)

~:表示指定的正则表达式要区分大小写

[root@master conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location ~^/test {
                echo "This is test!";
                
[root@master conf]# nginx -s reload

如下内容就可正确匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/test?abc123=a1b2
This is test!

如下内容则无法匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl http://192.168.58.10:8080/TEST/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl http://192.168.58.10:8080/testing
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

正则表达式模式匹配(不区分大小写)

~*:表示指定的正则表达式不区分大小写

[root@master conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location  ~*/test {
                echo "This is test!";
                
[root@master conf]# nginx -s reload

如下内容就可正确匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/test?abc123=a1b2
This is test!
[root@localhost ~]# curl http://192.168.58.10:8080/TEST
This is test!
[root@localhost ~]# 

如下内容则无法匹配

[root@localhost ~]# curl http://192.168.58.10:8080/test/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl http://192.168.58.10:8080/testing
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# 

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式
优先级次序
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )
查找顺序和优先级:由高到底依次为
1.带有=的精确匹配优先
2.正则表达式按照他们在配置文件中定义的顺序
3.带有^~修饰符的,开头匹配
4.带有~或~*修饰符的,如果正则表达式与URI匹配
5.没有修饰符的精确匹配

示例

root@master ~]# vim /usr/local/nginx/conf/nginx.conf
······
server {
        listen       8080;
        server_name  localhost;

        location /test {
            echo "1";
        }
        #"="优先级最高所以先注释掉
        #location = /test {
        #    echo "2";
        #}
        location ~^/test$ {
            echo "3";
        }
        location ~*/testi$ {
            echo "4";
        }
······

 [root@master ~]# nginx -s reload

优先级测试

[root@localhost ~]# curl http://192.168.58.10:8080/test
3
[root@localhost ~]# curl http://192.168.58.10:8080/testing
1
[root@localhost ~]# curl http://192.168.58.10:8080/TEST
4
[root@localhost ~]# curl http://192.168.58.10:8080/test?abc123=a1b2
3
[root@localhost ~]# curl http://192.168.58.10:8080/test/test
1
[root@localhost ~]# 

https配置

#创建证书存放目录
[root@master ~]# mkdir -p /etc/nginx/ssl
[root@master ~]# cd /etc/nginx/ssl/

#生成密钥
[root@master ssl]# openssl genrsa -out test.key 2048   
Generating RSA private key, 2048 bit long modulus (2 primes)
....................................................+++++
..+++++
e is 65537 (0x010001)

#生成证书
[root@master ssl]# openssl req -new -key test.key -out test.csr 
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HuBei
Locality Name (eg, city) [Default City]:WuHan
Organization Name (eg, company) [Default Company Ltd]:ssss
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:xm.com
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@master ssl]# ls
test.csr  test.key

[root@master ssl]# openssl x509 -req -days 365 -in test.csr -signkey test.key  -out test.crt
Signature ok
subject=C = CN, ST = HuBei, L = WuHan, O = ssss, CN = xm.com
Getting Private key
[root@master ssl]# ls
test.crt  test.csr  test.key

修改nginx配置文件

[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
······
//取消注释并修改域名和证书位置
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  www.xu.com;

        ssl_certificate      /etc/nginx/ssl/test.crt;
        ssl_certificate_key /etc/nginx/ssl/test.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;
        }
    }
······

[root@master ~]# nginx -s reload
[root@master ~]# ss -antl
State     Recv-Q     Send-Q         Local Address:Port         Peer Address:Port    
LISTEN    0          128                  0.0.0.0:443               0.0.0.0:*       
LISTEN    0          128                  0.0.0.0:80                0.0.0.0:*       
LISTEN    0          128                  0.0.0.0:22                0.0.0.0:*       
LISTEN    0          128                     [::]:22                   [::]:* 
访问测试

在这里插入图片描述

rewrite

rewrite作用

  • 不改变用户习惯
  • 访问的资源位置可以发生改变

语法:

rewrite regex replacement flag;

replacement可以是某个路径,也可以是某个URL

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容

意为将url开头为/imgs下所有的以.jpg结尾的文件路径全部转成 /images下所有.jpg结尾的文件

示例:
# 创建imgs文件夹
[root@master ~]# mkdir /usr/local/nginx/html/imgs
[root@master ~]# ls /usr/local/nginx/html/
50x.html  imgs  index.html  index.php

# 下载图片并移动到imgs中
[root@master ~]# mv tangseng.jpg /usr/local/nginx/html/imgs/
[root@master ~]# ls /usr/local/nginx/html/imgs/
tangseng.jpg

正常访问路径

http://192.168.58.10/imgs/tangseng.jpg

在这里插入图片描述

将imgs文件夹名字修改为images
[root@master ~]# mv /usr/local/nginx/html/imgs/ /usr/local/nginx/html/images/
[root@master ~]# ls /usr/local/nginx/html/
50x.html  images  index.html  index.php

# 修改配置文件
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
# 在server段插入以下内容
······
        location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;
        }
······


[root@master ~]# nginx -s reload

换个浏览器,再次访问imgs
在这里插入图片描述
html文件里夹没有imgs还是能访问到图片,由此可见rewrite配置成功

last和break组合使用示例

last 本条规则匹配完成后,继续向下匹配新的location URI规则
break 本条规则匹配完成即终止,不再匹配后面的任何规则

示例:
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
......
        #access_log  logs/host.access.log  main;

 location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ /images/$1 last;
        }

       location /images {
            rewrite ^/images/(.*\.jpg)$ http://images.baidu.com last;
        }

访问测试,浏览到百度页面
在这里插入图片描述
将break放到前面

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


location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;
        }

       location /images {
            rewrite ^/images/(.*\.jpg)$ http://images.baidu.com last;
        }

[root@master ~]# nginx -s reload

访问测试在这里插入图片描述

常见的flag
flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个 一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理 而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配 一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求, 且不再会被当前location内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
l匹配 l 之前或之后的实体
()分组,组成一组用于匹配的实体,通常会有

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hello sir”捕获的结果:$1=hello$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了

if
语法:

if (condition) {...}

应用场景:

  • server段
  • location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
  • 以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
  • 正则表达式的模式匹配操作
    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !和!*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)
  • 测试指定路径为目录的可能性(-d,!-d)
  • 测试文件的存在性(-e,!-e)
  • 检查文件是否有执行权限(-x,!-x)
举例
if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}

if ($request_method = POST) {
    return 405;
}

if ($slow) {
    limit_rate 10k;
}

if ($invalid_referer) {
    return 403;
}
基于浏览器实现分离案例
if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.itbaozi.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.itbaozi.com/403.html;
  }
}
nginx.conf配置文件案例
  1. 更改默认端口号以及进程数和指定特定配置文件

源(/usr/local/nginx/conf/)nginx.conf文件内容


[root@master conf]# pwd
/usr/local/nginx/conf
[root@master conf]# head nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;
.......
server {
        listen       80;
        server_name  localhost;
使用源文件运行进程数如下
[root@master opt]# ps -ef |grep nginx
root      535771       1  0 14:21 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     535772  535771  0 14:21 ?        00:00:00 nginx: worker process     //一个进程
root      535925    5312  0 14:21 pts/0    00:00:00 grep --color=auto nginx


//将源文件以及mime.types文件copy一份到/opt目录中
[root@master conf]# cp nginx.conf /opt/
[root@master conf]# cp mime.types /opt/
[root@master opt]# ls
mime.types  nginx.conf
[root@localhost opt]# nginx -t -c /opt/nginx.conf         //使用  -t   -s 参数测试语句
nginx: the configuration file /opt/nginx.conf syntax is ok
nginx: configuration file /opt/nginx.conf test is successful


##1 修改 worker_processes ;  参数为4
//设置所有worker进程最大可以打开的文件数
#user  nobody;
worker_processes 4;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;
.......
server {
        listen       8080;
        server_name  localhost;

使用nginx服务控制命令重启并指定配置文件路径
[root@master opt]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@master opt]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                           [::]:22                          [::]:*           
[root@master opt]# 

[root@master opt]# ps -ef | grep nginx
root      574422       1  0 14:44 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx     574423  574422  0 14:44 ?        00:00:00 nginx: worker process
nginx     574424  574422  0 14:44 ?        00:00:00 nginx: worker process
nginx     574425  574422  0 14:44 ?        00:00:00 nginx: worker process
nginx     574426  574422  0 14:44 ?        00:00:00 nginx: worker process
root      590466  558635  0 14:53 pts/0    00:00:00 grep --color=auto nginx
[root@master opt]# 

访问测试
在这里插入图片描述
2. 访问控制

注:用于location段,可以用主机地址表示,也可用网段表示,必须一起用
allow:设定允许那台或那些主机访问,多个参数间用空格隔开
deny:设定禁止那台或那些主机访问,多个参数间用空格隔开

环境说明:

主机名ip职责
master192.168.58.10nginx
localhost192.168.58.20client

例:

在matser主机上修改nginx配置文件,将192.168.58.0网段禁止访问

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

......
        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.58.10/32;
            deny   192.168.58.20/32;
        }
......
[root@master ~]# systemctl restart nginx
[root@master ~]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                              *:80                             *:*           
LISTEN        0             128                           [::]:22                          [::]:*       

在地址为192.168.58.20中访问

[root@localhost opt]# curl 192.168.58.10:8080
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

在 192.168.58.10中访问

[root@master ~]# curl 192.168.58.10:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

网页访问

在这里插入图片描述
将deny字段改为all,表示在拒绝所有主机访问

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

......
        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.58.10/32;  //只允许本机访问
            deny   all;
        }
......
[root@master ~]# systemctl restart nginx
[root@master ~]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                              *:80                             *:*           
LISTEN        0             128                           [::]:22                          [::]:*       

测试

[root@master ~]# curl 192.168.58.10:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

3.基于用户认证

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file";

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

实例
 #安装httpd-tools
[root@master ~]# yum -y install httpd-tools

#确保用户不存在
[root@master ~]# id xu
id: “xu”:无此用户

#生成用户认证文件
[root@master ~]# htpasswd -c -m /usr/local/nginx/conf/.user-auth-file xu
New password: 
Re-type new password: 
Adding password for user xu
[root@master ~]# cat /usr/local/nginx/conf/.user-auth-file 
xu:$apr1$wxonSrbv$XbB3A8Nxr7yypySk5Kk1d.

#创建测试文件
[root@master ~]# mkdir -p /usr/local/nginx/html/xu
[root@master ~]# echo "welcome to xu!" > /usr/local/nginx/html/xu/index.html
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
······
server {
        listen       8080;
        server_name  localhost;

           location /xu {
                root html;
                index index.html;
                auth_basic "Hello,xu!";
                auth_basic_user_file "/usr/local/nginx/conf/.user-auth-file";

#检测语法并重载配置文件,
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@master ~]# nginx -s reload
[root@master ~]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                              *:80                             *:*           
LISTEN        0             128                           [::]:22                          [::]:*           
访问测试

在这里插入图片描述
在这里插入图片描述

4.用于调试、定位问题
是否以守护进程方式运行Nginx
守护进程(daemon)是脱离终端并且在后台运行的进程。它脱离终端是为了避免进程执行过程中的信息在任何终端上显示,这样一来,进程也不会被任何终端所产生的信息所打断。Nginx毫无疑问是一个需要以守护进程方式运行的服务,因此,默认都是以这种方式运行的。

不过Nginx还是提供了关闭守护进程的模式,之所以提供这种模式,是为了方便跟踪调试Nginx,毕竟用gdb调试进程时最烦琐的就是如何继续跟进fork出的子进程了。

//daemon {on|off};    #是否以守护进程方式运行nginx,调试时应设置为off
[root@master ~]# head -5 /opt/nginx.conf 

#user  nobody;
worker_processes  4;
daemon off;
[root@master conf]# nginx -s stop;nginx -c /opt/nginx.conf 


网页访问
在这里插入图片描述
5.开启状态页面
开启status:

vim /usr/local/nginx/conf/nginx.conf

location /status {
          stub_status on;
          allow 192.168.58.0/24;
          deny all;
        }

访问状态页面的方式:http://server_ip/status

在这里插入图片描述

状态页面信息详解:
状态码表示的意义
Active connections 2当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
Readingnginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writingnginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),

意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

状态页面监控

环境说明

主机名ip职责
master192.168.58.10nginx、zabbix_agent
zabbix192.168.58.120zabbix_server

准备工作:

#nginx

//关闭防火墙和SELINUX
[root@master ~]# systemctl disable --now firewalld
[root@master ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@master ~]# setenforce 0

//安装依赖包
[root@master ~]# yum -y install gcc gcc-c++ bzip2 pcre* make
[root@master ~]# wget https://cdn.zabbix.com/zabbix/sources/stable/5.2/zabbix-5.2.6.tar.gz
[root@master ~]# tar xf zabbix-5.2.6.tar.gz 
[root@master ~]# useradd -r -M -s /sbin/nologin zabbix
[root@master ~]# cd zabbix-5.2.6/
[root@master zabbix-5.2.6]# ./configure --enable-agent
[root@master zabbix-5.2.6]# make install

//修改配置文件
[root@master ~]# vim /usr/local/etc/zabbix_agentd.conf
······
Server=192.168.58.120			#修改成服务端IP
······
ServerActive=192.168.58.120		#修改成服务端IP
······
Hostname=nginx

[root@master ~]# zabbix_agentd 
[root@master ~]# ss -antl
State     Recv-Q    Send-Q         Local Address:Port          Peer Address:Port    
LISTEN    0         128                  0.0.0.0:10050              0.0.0.0:*       
LISTEN    0         128                  0.0.0.0:80                 0.0.0.0:*       
LISTEN    0         128                  0.0.0.0:22                 0.0.0.0:*       
LISTEN    0         128                     [::]:22                    [::]:*      
编写监控脚本
# master

//创建脚本存放目录
[root@master ~]# mkdir /scripts
[root@master ~]# cd /scripts/
[root@master scripts]# chown zabbix.zabbix /scripts/
[root@master scripts]# ll / |grep zabbix
drwxr-xr-x.   2 zabbix zabbix    6 10月 28 10:23 scripts

//编写监控脚本
[root@master scripts]# vim check_nginx_Reading.sh 
#! /bin/bash
Reading=`curl -s http://192.168.58.10/status | awk 'NR==4{print $2}'`
    echo $Reading


[root@master scripts]# vim check_nginx_requests.sh 
#! /bin/bash

requests=`curl -s http://192.168.58.10/status | awk 'NR==3{print $3}'`
    echo $requests


[root@master scripts]# vim check_nginx_Writing.sh 
# /bin/bash

Writing=`curl -s http://192.168.58.10/status | awk 'NR==4{print $4}'`
    echo $Writing


[root@master scripts]# vim check_nginx_Waiting.sh 
#! /bin/bash

Waiting=`curl -s http://192.168.58.10/status | awk 'NR==4{print $6}'`
    echo $Waiting


[root@master scripts]# chmod +x check_nginx_*.sh
[root@master scripts]# ll .
总用量 16
-rwxr-xr-x. 1 root root 101 10月 28 10:59 check_nginx_Reading.sh
-rwxr-xr-x. 1 root root 104 10月 28 10:56 check_nginx_requests.sh
-rwxr-xr-x. 1 root root 102 10月 28 11:04 check_nginx_Waiting.sh
-rwxr-xr-x. 1 root root 101 10月 28 11:03 check_nginx_Writing.sh


修改zabbix_agentd.conf配置文件,添加指标

#zabbix

//在最下端添加以下内容
UnsafeUserParameters=1
UserParameter=check_nginx_requests,/scripts/check_nginx_requests.sh
UserParameter=check_nginx_Reading,/scripts/check_nginx_Reading.sh
UserParameter=check_nginx_Writing,/scripts/check_nginx_Writing.sh
UserParameter=check_nginx_Waiting,/scripts/check_nginx_Waiting.sh


//重启zabbix_agentd
[root@master scripts]# pkill zabbix_agentd 
[root@master scripts]# zabbix_agentd
[root@master scripts]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:10050                    0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:80                       0.0.0.0:*           
LISTEN        0             128                           [::]:22                          [::]:*        

测试是否能够获取到客户端的指标

#zabbix


[root@zabbix ~]# zabbix_get -s 192.168.58.10 -k check_nginx_Reading
0
[root@zabbix ~]# zabbix_get -s 192.168.58.10 -k check_nginx_Waiting
0
[root@zabbix ~]# zabbix_get -s 192.168.58.10 -k check_nginx_Writing
1
[root@zabbix ~]# zabbix_get -s 192.168.58.10 -k check_nginx_requests
37

Web界面配置

创建nginx主机组
在这里插入图片描述

在这里插入图片描述
创建主机
在这里插入图片描述
在这里插入图片描述
添加监控项
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
添加一个图表
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查看图表
在这里插入图片描述
在这里插入图片描述

Nginx实现负载均衡和动静分离

环境说明:

主机名ip职责
master192.168.58.10apache
lnmp192.168.58.20lnmp
nginx192.168.58.30nginx

环境准备:

apache

关闭防火墙

[root@master ~]# systemctl disable --now  firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@master ~]# setenforce 0
[root@master ~]# vi /etc/selinux/config 
SELINUX=disabled

下载apr 、apr-util 、httpd-2.4.48压缩包

[root@master ~]# wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.gz
[root@master ~]# wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util-1.6.1.tar.gz
[root@master ~]# wget https://mirrors.tuna.tsinghua.edu.cn/apache/httpd/httpd-2.4.48.tar.gz

[root@master ~]# ls
anaconda-ks.cfg  apr-1.7.0.tar.gz  apr-util-1.6.1.tar.gz  httpd-2.4.48.tar.gz
[root@master ~]# mv apr-1.7.0.tar.gz  apr-util-1.6.1.tar.gz httpd-2.4.48.tar.gz /usr/src
[root@master src]# ls
apr-1.7.0.tar.gz  apr-util-1.6.1.tar.gz  debug  httpd-2.4.48.tar.gz  kernels

安装依赖包

yum -y install openssl-devel pcre-devel expat-devel libtool 

创建apache用户和组

[root@master ~]# groupadd -r apache
[root@masyer ~]# useradd -r -M -s /sbin/nologin -g apache apache 

编译 apr、apr-util

[root@master src]# cd apr-1.7.0/
[root@master apr-1.7.0]# ls
apr-config.in  build.conf        dso         libapr.rc     NOTICE         support
apr.dep        buildconf         emacs-mode  LICENSE       NWGNUmakefile  tables
apr.dsp        build-outputs.mk  encoding    locks         passwd         test
apr.dsw        CHANGES           file_io     Makefile.in   poll           threadproc
apr.mak        CMakeLists.txt    helpers     Makefile.win  random         time
apr.pc.in      config.layout     include     memory        README         tools
apr.spec       configure         libapr.dep  misc          README.cmake   user
atomic         configure.in      libapr.dsp  mmap          shmem
build          docs              libapr.mak  network_io    strings
[root@master apr-1.7.0]# vim configure
    cfgfile="${ofile}T"
    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
    # $RM "$cfgfile"        //将此行加上注释,或者删除此行
[root@master apr-1.7.0]# ./configure --prefix=/usr/local/apr
配置过程略...
[root@master apr-1.7.0]# make && make install
编译安装过程略...

[root@master apr-1.7.0]# cd /usr/src/apr-util-1.6.1
[root@master apr-util-1.6.1]# ./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr
配置过程略...
[root@master apr-util-1.6.1]# make && make install
编译安装过程略...

编译httpd

[root@master src]# tar xf httpd-2.4.48.tar.gz
[root@master src]# cd httpd-2.4.48/
[root@master httpd-2.4.48]# ./configure --prefix=/usr/local/apache \
> --sysconfdir=/etc/httpd24 \
> --enable-so \
> --enable-ssl \
> --enable-cgi \
> --enable-rewrite \
> --with-zlib \
> --with-pcre \
> --with-apr=/usr/local/apr \
> --with-apr-util=/usr/local/apr-util/ \
> --enable-modules=most \
> --enable-mpms-shared=all \
> --with-mpm=prefork

[root@master httpd-2.4.48]# make && make install
编译安装过程略...

配置环境变量

[root@master ~]# echo 'export PATH=/usr/local/apache/bin:$PATH' > /etc/profile.d/httpd.sh
[root@master ~]# source /etc/profile.d/httpd.sh
[root@master ~]# ln -s /usr/local/apache/include/ /usr/include/httpd
[root@master ~]# echo 'MANPATH /usr/local/apache/man' >> /etc/man.config

取消ServerName前面的注释

[root@master ~]# sed -i '/#ServerName/s/#//g' /etc/httpd24/httpd.conf 

配置service文件

[root@master ~]# cat > /usr/lib/systemd/system/httpd.service  << EOF
[Unit]
Description=The Apache http server
After=network.targe

[Service]
Type=forking
ExecStart=/usr/local/httpd/bin/apachectl start
ExecStop=/usr/local/httpd/bin/apachectl stop
ExecReload=/bin/kill -HUP \$MAINPID

[Install]
WantedBy=multi-user.target
EOF

启动服务

[root@master ~]# systemctl daemon-reload
[root@master ~]# systemctl enable --now httpd
[root@master ~]# ss -anlt
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*        
LISTEN      0           128                          *:80                        *:*        
LISTEN      0           128                       [::]:22                     [::]:*        

在上面的准备工作完成后,访问测试
master(192.168.58.10)
在这里插入图片描述

LNMP

Nginx

关闭防火墙

[root@lnmp ~]# systemctl disable --now  firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@lnmp ~]# setenforce 0
[root@lnmp ~]# vi /etc/selinux/config 
SELINUX=disabled

下载Nginx包

[root@lnmp ~]# wget http://nginx.org/download/nginx-1.20.1.tar.gz
[root@lnmp ~]# mv nginx-1.20.1.tar.gz /usr/src

创建用户nginx

[root@lnmp ~]# useradd -r -M -s /sbin/nologin nginx

安装依赖包

[root@lnmp ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@lnmp ~]# yum -y groups mark install 'Development Tools'

创建日志存放目录

[root@lnmp ~]#  mkdir -p /var/log/nginx
[root@lnmp ~]# chown -R nginx.nginx /var/log/nginx

编译安装nginx

[root@lnmp ~]# cd /usr/src/
[root@lnmp src]# ls
debug    mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz  php-8.0.10.tar.xz
kernels  nginx-1.20.1.tar.gz
[root@lnmp src]# tar xf nginx-1.20.1.tar.gz 
[root@lnmp src]# cd nginx-1.20.1
[root@lnmp nginx-1.20.1]#./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@lnmp nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
编译过程略.....

配置环境变量

[root@lnmp ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@lnmp ~]# source /etc/profile.d/nginx.sh

启动nginx

[root@lnmp ~]# /usr/local/nginx/sbin/nginx     //默认启动文件
[root@lnmp ~]# ss -antl
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port  Process   
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*               
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*               
LISTEN   0        128                 [::]:22               [::]:*         

Mysql

下载二进制包

[root@lnmp ~]# wget https://dev.mysql.com/downloads/file/?id=507442

安装依赖包

[root@lnmp ~]# yum -y install ncurses-devel openssl-devel openssl cmake mariadb-devel ncurses-compat-libs

创建用户和组

[root@lnmp ~]# useradd -r -M -s /sbin/nologin mysql

解压mysql软件包

[root@lnmp ~]# cd /usr/src/
[root@lnmp src]# tar xf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@lnmp ~]# cd /usr/local/
[root@lnmp local]# ls
bin  games    lib    libexec                              nginx  share
etc  include  lib64  mysql-5.7.35-linux-glibc2.12-x86_64  sbin   src
[root@lnmp local]# ln -sv mysql-5.7.35-linux-glibc2.12-x86_64/ mysql
'mysql' -> 'mysql-5.7.35-linux-glibc2.12-x86_64/'
[root@lnmp local]# chown -R mysql.mysql /usr/local/mysql*

添加环境变量

[root@lnmp ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@lnmp ~]# source /etc/profile.d/mysql.sh
[root@lnmp ~]# echo $PATH 
/usr/local/mysql/bin:/usr/local/nginx/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

软连接

[root@lnmp ~]# ln -s /usr/local/mysql/include /usr/include/mysql

配置帮助文档

[root@lnmp ~]# vim /etc/man_db.conf
MANDATORY_MANPATH                       /usr/local/mysql/man

配置库文件

[root@lnmp ~]# vim /etc/ld.so.conf.d/mysql.conf
/usr/local/mysql/lib
[root@lnmp ~]# ldconfig 

创建数据存放目录

[root@lnmp ~]# mkdir -p /opt/data
[root@lnmp ~]# chown -R mysql.mysql /opt/data/
[root@lnmp ~]# ll /opt/
总用量 0
drwxr-xr-x. 2 mysql mysql 6 10月 26 01:02 data

初始化数据库

[root@lnmp ~]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/data
初始化过程略......

生成配置文件

[root@lnmp ~]# cat /etc/my.cnf    #如果这个文件存在,请先备份再修改
[mysqld]
basedir = /usr/local/mysql
datadir = /data
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/mysql.pid
user = mysql
skip-name-resolve

配置启动服务

[root@lnmp ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /usr/local/mysql/support-files/mysql.server 
[root@lnmp ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /usr/local/mysql/support-files/mysql.server
[root@lnmp ~]# cat /usr/lib/systemd/system/mysqld.service
[Unit]
Description=Mysql server daemon
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/mysql/support-files/mysql.server start
ExecStop=/usr/local/mysql/support-files/mysql.server stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target

启动mysql

[root@lnmp ~]# systemctl daemon-reload 
[root@lnmp ~]# systemctl enable --now mysqld
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@lnmp ~]# ss -antl
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port  Process   
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*               
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*               
LISTEN   0        128                 [::]:22               [::]:*               
LISTEN   0        80                     *:3306                *:*              

设置数据库密码

mysql> set password = password('123456');
Query OK, 0 rows affected, 1 warning (0.00 sec)

PHP

下载php安装包

[root@lnmp ~]# wget https://www.php.net/distributions/php-8.0.10.tar.gz

首先下载epel源,确保依赖包的完整性

[root@lnmp ~]# yum -y install epel-release

下载依赖包

[root@lnmp ~]# yum -y install libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel libcurl libcurl-devel libicu-devel libjpeg libjpeg-devel libpng libpng-devel openldap-devel  pcre-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel mhash mhash-devel php-mysqlnd libzip-devel.x86_64 libsqlite3x-devel

[root@lnmp ~]# yum -y install http://mirror.centos.org/centos/8-stream/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm

解压编译PHP

[root@lnmp ~]# cd /usr/src/
[root@lnmp src]# tar xf php-8.0.10.tar.xz 
[root@lnmp src]# cd php-8.0.10
[root@lnmp php-8.0.10]#./configure --prefix=/usr/local/php8  \
--with-config-file-path=/etc \
--enable-fpm \
--disable-debug \
--disable-rpath \
--enable-shared \
--enable-soap \
--with-openssl \
--enable-bcmath \
--with-iconv \
--with-bz2 \
--enable-calendar \
--with-curl \
--enable-exif  \
--enable-ftp \
--enable-gd \
--with-jpeg \
--with-zlib-dir \
--with-freetype \
--with-gettext \
--enable-mbstring \
--enable-pdo \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-readline \
--enable-shmop \
--enable-simplexml \
--enable-sockets \
--with-zip \
--enable-mysqlnd-compression-support \
--with-pear \
--enable-pcntl \
--enable-posix

[root@lnmp php-8.0.10]# make && make install
编译过程略.....

设置环境变量

[root@lnmp php-8.0.10]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh
[root@lnmp php-8.0.10]# source /etc/profile.d/php.sh

配置php-fpm

[root@lnmp php-8.0.10]# cp php.ini-production /etc/php.ini
cp:是否覆盖'/etc/php.ini'? y
[root@lnmp php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@lnmp php-8.0.10]# chmod +x /etc/init.d/php-fpm
[root@lnmp php-8.0.10]# cp /usr/local/php8/etc/php-fpm.conf.default /usr/local/php8/etc/php-fpm.conf
[root@lnmp php-8.0.10]# cp /usr/local/php8/etc/php-fpm.d/www.conf.default /usr/local/php8/etc/php-fpm.d/www.conf

启动php-fpm

[root@lnmp ~]# service php-fpm start
Starting php-fpm  done
[root@lnmp ~]# ss -antl
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port  Process   
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*               
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*               
LISTEN   0        128            127.0.0.1:9000          0.0.0.0:*               
LISTEN   0        128                 [::]:22               [::]:*               
LISTEN   0        80                     *:3306                *:*    

创建php测试页面

[root@lnmp ~]# cat /usr/local/nginx/html/index.php
<?php
    phpinfo();
?>

配置nginx

[root@lnmp ~]# vim /usr/local/nginx/conf/nginx.conf
......
http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.php index.html index.htm;				#添加index.php
        }
        location ~ \.php$ {
            root   html;
            fastcgi_pass   127.0.0.1:9000;                      #在工作中这里要改为php服务器的地址
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $Document_Root$fastcgi_script_name;
            include        fastcgi_params;
        }

......

重新加载配置文件

[root@lnmp ~]# nginx -s reload
[root@lnmp ~]# ss -antl
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port  Process   
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*               
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*               
LISTEN   0        128            127.0.0.1:9000          0.0.0.0:*               
LISTEN   0        128                 [::]:22               [::]:*               
LISTEN   0        80                     *:3306                *:*    

访问lnmp(192.168.58.20)主机web页面
在这里插入图片描述

nginx主机部署nginx服务

关闭防火墙

[root@nginx ~]# systemctl disable --now  firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@nginx ~]# setenforce 0
[root@nginx ~]# vi /etc/selinux/config 
SELINUX=disabled

下载Nginx包

[root@nginx ~]# wget http://nginx.org/download/nginx-1.20.1.tar.gz
[root@nginx ~]# mv nginx-1.20.1.tar.gz /usr/src

创建用户nginx

[root@nginx ~]# useradd -r -M -s /sbin/nologin nginx

安装依赖环境

[root@nginx ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@nginx ~]# yum -y groups mark install 'Development Tools'

创建日志存放目录

[root@nginx ~]#  mkdir -p /var/log/nginx
[root@nginx ~]# chown -R nginx.nginx /var/log/nginx

编译安装nginx

[root@nginx ~]# cd /usr/src/
[root@nginx src]# ls
debug    mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz  php-8.0.10.tar.xz
kernels  nginx-1.20.1.tar.gz
[root@nginx src]# tar xf nginx-1.20.1.tar.gz 
[root@nginx src]# cd nginx-1.20.1
[root@nginx nginx-1.20.1]#./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@nginx nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

配置环境变量

[root@nginx ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@nginx ~]# source /etc/profile.d/nginx.sh

启动nginx

[root@nginx ~]# /usr/local/nginx/sbin/nginx     //默认启动文件
[root@nginx ~]# ss -antl
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port  Process   
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*               
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*               
LISTEN   0        128                 [::]:22               [::]:*         

访问nginx主机(192.168.58.30)web页面
在这里插入图片描述
以上步骤都完成后即可开始配置nginx负载

在nginx主机上配置负载均衡
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
    ······
    upstream test {
       server 192.168.58.10;
       server 192.168.58.20;
    }


    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
    location / {
        proxy_pass http://test;
}
  ······
  

[root@client ~]# nginx -s reload 

负载测试反复访问ningx(192.168.58.30)主机web页面
在这里插入图片描述
在这里插入图片描述
发现两个网页,交替显示

动静分离

在上面的环境下实现

在nginx主机上配置动静分离
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
upstream static {
       server 192.168.58.10;
    }

    upstream dynamic {
       server 192.168.58.20;
    }


    server {
        listen       80;
        server_name  localhost;

    location / {
        proxy_pass http://static;
    }

    location ~ \.php$ {
        proxy_pass http://dynamic;
    }
......

[root@client ~]# nginx -s reload

访问测试(访问client(192.168.58.30))
此处的访问页面源于master上的测试页面
在这里插入图片描述
此处访问的是lnmp主机的页面
在这里插入图片描述
通过使用nginx将两个页面分开负载显示,极大的提高了源服务器的工作效率

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值