Nginx

2 篇文章 0 订阅
1 篇文章 0 订阅

1 nginx介绍

Nginx (“engine x”) 是一个开源的,支持高性能、高并发的 Web 服务和代理服务软件。它是由俄罗斯人 Igor Sysoev 开发的,最初被应用在俄罗斯的大型网站 www.rambler.ru 上。后来作者将源代码以类 BSD 许可的形式开源出来供全球使用

Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。

Nginx是一款轻量级的Web服务器/反向代理服务器以及电子邮件代理服务器。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好。

Nginx相较于Apache\lighttpd具有占有内存少,稳定性高等优势,并且依靠并发能力强,丰富的模块库以及友好灵活的配置而闻名。在Linux操作系统下,nginx使用epoll事件模型,得益于此,nginx在Linux操作系统下效率相当高

2 nginx的特性与优点

2.1 Nginx 特性

  • 可针对静态资源高速高并发访问及缓存。
  • 可使用反向代理加速,并且可进行数据缓存。
  • 具有简单负载均衡、节点健康检查和容错功能。
  • 支持远程 FastCGI 服务的缓存加速。
  • 支持 FastCGI、Uwsgi、SCGI、Memcached Servers 的加速和缓存。
  • 支持SSL、TLS、SNI。
  • 具有模块化的架构:过滤器包括 gzip 压缩、ranges 支持、chunked 响应、XSLT、SSI 及图像缩放等功能。在SSI 过滤中,一个包含多个 SSI 的页面,如果经由 FastCGI 或反向代理,可被并行处理。
  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

2.1 Nginx Web 服务特性

  • 支持基于名字、端口及IP的多虚拟主机站点。
  • 支持 Keep-alive 和 pipelined 连接。
  • 可进行简单、方便、灵活的配置和管理。
  • 支持修改 Nginx 配置,并且在代码上线时,可平滑重启,不中断业务访问。
  • 可自定义访问日志格式,临时缓冲写日志操作,快速日志轮询及通过 rsyslog 处理日志。
  • 可利用信号控制 Nginx 进程。
  • 支持 3xx-5xx HTTP状态码重定向。
  • 支持 rewrite 模块,支持 URI 重写及正则表达式匹配。
  • 支持基于客户端 IP 地址和 HTTP 基本认证的访问控制。
  • 支持 PUT、DELETE、MKCOL、COPY 及 MOVE 等特殊的 HTTP 请求方法。
  • 支持 FLV 流和 MP4 流技术产品应用。
  • 支持 HTTP 响应速率限制。
  • 支持同一 IP 地址的并发连接或请求数限制。
  • 支持邮件服务代理。

2.3 nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均- 衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

2.4 nginx的缺点

  • 动态处理能力差:Nginx善于处理静态文件,但是处理动态页面的能力相较于Apache之类的重量级web软件能力稍差。

  • rewrite弱:虽然nginx支持rewrite功能多,但是相较于Apache之类的重量级的web软件能力稍差。

3 nginx的功能及应用类别

3.1 基本功能

  • 实现与服务静态文件(静态资源的web服务器),能缓存打开的文件描述符;
  • 反向代理服务器,缓存、负载均衡、健康状态检测;
  • 支持FastCGI;
  • 缓存加速、负载均衡
  • 模块化机制,非DSO机制,支持多种过滤器gzip,SSI和图像的模块完成图形大小调整等;
  • 支持SSL;

3.2 扩展功能

  • 基于名称和IP做虚拟主机;
  • 支持keeplive;
  • 支持平滑配置更新或程序版本升级;
  • 定制访问日志,支持使用日志缓存以提高性能;
  • 支持URL rewrite;
  • 支持路径别名;
  • 支持基于IP及用户的认证;
  • 支持速率限制,并发数限制等;

3.3 nginx的应用类别

  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
  • 使用nginx作反向代理、负载均衡、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用

4 nginx的模块

nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作

4.1 nginx的模块分类

在这里插入图片描述

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

  • HTTP模块、EVENT模块和MAIL模块等属于核心模块
  • HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
  • HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

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

nginx模块从功能上分为三类

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

nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

  • nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
    • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部
    • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
    • 配置模块:提供包含机制

5 nginx的工作原理

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

Nginx的模块直接被编译进Nginx,因此属于静态编译方式。启动Nginx后,Nginx的模块被自动加载,不像Apache,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。在解析配置文件时,Nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成

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

在这里插入图片描述
Nginx主要由一个master主进程和多个worker进程

  • master主进程主要是管理worker进程,对网络事件进行收集和分发:
    1. 接收来自外界的信号
    2. 向各worker进程发送信号
    3. 监控worker进程的运行状态,当worker进程退出后(异常情况下),会自动重新启动新的worker进程
  • nginx用一个独立的worker进程来处理一个请求,一个worker进程可以处理多个请求:
  • 当一个worker进程在accept这个连接之后,就开始读取请求,解析请求,处理请求,产生数据后,再返回给客户端,最后才断开连接。
    一个请求,完全由worker进程来处理,而且只在一个worker进程中处理。采用这种方式的好处
    1. 节省锁带来的开销。对于每个worker进程来说,独立的进程,不需要加锁,所以省掉了锁带来的开销,同时在编程以及问题查上时,也会方便很多
    2. 独立进程,减少风险。
    3. 采用独立的进程,可以让互相之间不会影响,一个进程退出后,其它进程还在工作,服务不会中断,master进程则很快重新启动新的worker进程。
    4. 在一次请求里无需进程切换

5.1 web服务器请求资源过程

在这里插入图片描述
1.客户端发起请求,然后与服务端建立tcp连接
2.服务器接收请求
3.进行反向代理,然后服务器处理请求
4.查看访问资源的类型(可能是本地的资源,也可能是通过NFS挂载的资源)
5.构建响应报文
6.通过网络接口返回响应报文给客户端
7.服务端将本次的操作记录到日志中
在这里插入图片描述
详细流程
client:输入网址–>发起http request–>等待web server响应.
server:收到client请求–>加载资源–>构建响应报文,发给client.

client发起http请求

  1. client将键入的域名解析为server端的IP地址(DNS解析).

  2. client与server进行TCP连接(三次握手).

  3. client与web server数据传输.

  4. client与web server断开TCP连接(四次挥手).

  5. client解释HTML文档,浏览器渲染,将在屏幕上显示渲染后的图形结果

server收到client请求时

  1. http request请求首先到达server端的公网ip上(公网ip一般配置在硬件防火墙上).

  2. 经过防火墙过滤之后,到达负载均衡层(可能涉及四层负载均衡和七层负载均衡),负载均衡将请求报文往后端Real Server调度.

  3. 经过lvs调度至后端RS上,此时后端提供web服务的一般是Nginx(Apache也可能),Nginx判断请求报文是动态资源还是静态资源(动静分离).

  4. 静态资源:由Nginx发起系统调用,请求内核从磁盘加载相应的资源文件,可能涉及存储服务器(资源的保存的服务器).
    动态资源:由Nginx代理给能处理动态资源的服务器(Tomcat、PHP等),还可能涉及访问数据库服务器.

  5. web server将请求的资源加载完成之后,构建响应报文发送给client.

6 nginx安装与配置

环境说明

系统IP
centos8192.168.25.147
//创建系统用户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++
[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/local/src/
[root@Nginx src]# wget http://nginx.org/download/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  && make install

// 启动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               [::]:*        

6.1 nginx安装后配置

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



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


[root@Nginx ~]# 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@Nginx ~]# nginx -v    //查看nginx的版本
nginx version: nginx/1.20.1


[root@Nginx ~]# nginx -V    // 查看更加详细的信息
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --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 -h    //查看帮助
nginx version: nginx/1.20.1
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/local/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file


// 修改配置文件的方法
[root@Nginx conf]# cp nginx.conf /opt/
[root@Nginx conf]# cp mime.types /opt/
[root@Nginx opt]# ls
mime.types  nginx.conf
[root@Nginx opt]# vim nginx.conf 
#user  nobody;
worker_processes  1;
[root@Nginx ~]# nginx -s stop;nginx -c /opt/nginx.conf     //指定配置文件的路径
root@Nginx ~]# ps -ef | grep nginx
root        1817       1  0 04:42 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx       1818    1817  0 04:42 ?        00:00:00 nginx: worker process
root        1821    1734  0 04:42 pts/0    00:00:00 grep --color=auto nginx




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

[root@Nginx ~]# nginx -s reload    //发送服务控制信号,重新加载配置文件
[root@Nginx ~]# ps -ef | grep nginx
root        1725       1  0 04:10 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1769    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1770    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1771    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1772    1725  0 04:22 ?        00:00:00 nginx: worker process
root        1779    1734  0 04:22 pts/0    00:00:00 grep --color=auto nginx

7 nginx的配置文件详解

主配置文件:安装路径/conf/nginx.conf

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

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

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

7.1 nginx.conf配置详解

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

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置

配置指令:要以分号结尾,语法格式如下

derective value1 [value2 ...];

支持使用变量

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value

7.2 用于调试、定位问题的配置参数

daemon {on|off}; //是否以守护进程方式运行nginx,调试时应设置为off

//用法
Syntax:	daemon on | off;					#语法
Default: daemon on;	 						#默认值
Context:	main							#可以配置在那个字段中

[root@Nginx ~]# vim /opt/nginx.conf 
#user  nobody;
worker_processes  1;
daemon off;

//重启nginx
[root@Nginx ~]# nginx -s stop;nginx -c /opt/nginx.conf
[root@Nginx ~]# nginx -s stop
[root@Nginx ~]# nginx
//此时nginx将不会以守护进程的方式运行,会一直占据着前台屏幕                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

master_process {on|off}; //是否以master/worker模型来运行nginx,调试时可以设置为off

//用法
Syntax:	master_process on | off;
Default:  master_process on;
Context:  main

//nginx默认是以master/worker模型来运行
[root@Nginx ~]# ps -ef | grep nginx
root        1777       1  0 08:01 ?        00:00:00 nginx: master process nginx
nginx       1778    1777  0 08:01 ?        00:00:00 nginx: worker process
root        1800    1779  0 08:02 pts/0    00:00:00 grep --color=auto nginx

[root@Nginx ~]# vim /opt/nginx.conf 
#user  nobody;
worker_processes  1;
master_process off;


//重读nginx配置文件
[root@Nginx ~]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@Nginx ~]# ps -ef | grep nginx
root        1804       1  0 08:04 ?        00:00:00 nginx -c /opt/nginx.conf
root        1806    1779  0 08:04 pts/0    00:00:00 grep --color=auto nginx

error_log 位置 级别; //配置错误日志

//用法,在不同的字段有不同的含义,比如在main字段写就会对整个nginx产生影响,在http字段写就会对某个网站产生影响
Syntax:	error_log file [level];
Default: error_log logs/error.log error;
Context:  main, http, mail, stream, server, location

[root@Nginx ~]# vim /opt/nginx.conf 
#user  nobody;
worker_processes  1;

error_log  logs/error.log;    //没有写记录日志的级别,表示默认记录error级别的日志

//重读nginx配置文件
[root@Nginx ~]# vim /opt/nginx.conf 
[root@Nginx ~]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@Nginx ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid

//访问一个不存在的资源
[root@Nginx ~]# curl http://192.168.25.147/tt.txt
<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@Nginx ~]# tail -f /usr/local/nginx/logs/error.log
2021/10/25 08:13:45 [error] 1817#0: *1 open() "/usr/local/nginx/html/tt.txt" failed (2: No such file or directory), client: 192.168.25.147, server: localhost, request: "GET /tt.txt HTTP/1.1", host: "192.168.25.147"

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

位置含义
file记录到某个文件中
stdree记录到标准错误中(不推荐)
syslog:server=address[,parameter=value]记录到某台日志服务器中
memory:size记录到内存中(不推荐)
日志级别含义
debug若要使用debug级别,需要在编译nginx时使用–with-debug选项
info一般信息
notice不影响正常功能,需要注意的消息
warn可能影响系统功能,需要提醒用户的重要事件
error错误信息(常用的)
crit紧急,比较严重的
alert必须马上处理的
emerg会导致系统不可用的

7.3 正常运行必备的配置参数

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

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

[root@Nginx ~]# 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@Nginx ~]# 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;

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

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

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

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

7.4 优化性能的配置参数

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

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

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

[root@Nginx ~]# nginx -s reload    //发送服务控制信号,重新加载配置文件
[root@Nginx ~]# ps -ef | grep nginx
root        1725       1  0 04:10 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1769    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1770    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1771    1725  0 04:22 ?        00:00:00 nginx: worker process
nginx       1772    1725  0 04:22 ?        00:00:00 nginx: worker process
root        1779    1734  0 04:22 pts/0    00:00:00 grep --color=auto nginx
注: worker_processes的数量*worker_connections的数量=nginx所能支持的最大并发连接数量,在实际情况最大并发数建议不超过30000

worker_cpu_affinity cpumask …; 将进程绑定到某cpu中,避免频繁刷新缓存,似于专人专事,建议不要把所有的cpu都绑定,至少留一个cpu来让系统正常运行

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

//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核心

特殊值 (1.9.10) 允许将工作进程自动绑定到可用的 CPU:auto
worker_processes auto;
worker_cpu_affinity auto;
可选掩码参数可用于限制可用于自动绑定的 CPU:
worker_cpu_affinity auto 01010101;
该指令仅在 FreeBSD 和 Linux 上可用。


[root@Nginx ~]# nproc        #查看cpu的核心数
4
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes 3 ;
worker_cpu_affinity 0001 0010 0100;    #将进程绑定在0,1,2cpu核心上运行

[root@Nginx ~]# ps -ef | grep nginx
root        1996    1514  0 02:58 pts/0    00:00:00 vim /opt/nginx.conf
root        2072       1  0 03:18 ?        00:00:00 nginx: master process nginx
nginx       2073    2072  0 03:18 ?        00:00:00 nginx: worker process
nginx       2074    2072  0 03:18 ?        00:00:00 nginx: worker process
nginx       2075    2072  0 03:18 ?        00:00:00 nginx: worker process
root        2078    2025  0 03:18 pts/1    00:00:00 grep --color=auto nginx

在这里插入图片描述

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

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

worker_priority number; 指明worker进程的nice值

//用法
Syntax:	worker_priority number;
Default:	
worker_priority 0;
Context:	main

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

[root@Nginx ~]# ps -elf | grep nginx
0 S root        1996    1514  0  80   0 - 11868 core_s 02:58 pts/0    00:00:00 vim /opt/nginx.conf
1 S root        2109       1  0  80   0 - 20408 -      03:36 ?        00:00:00 nginx: master process nginx
5 S nginx       2110    2109  0  60 -20 - 28556 do_epo 03:36 ?        00:00:00 nginx: worker process
5 S nginx       2111    2109  0  60 -20 - 28556 do_epo 03:36 ?        00:00:00 nginx: worker process
5 S nginx       2112    2109  0  60 -20 - 28556 do_epo 03:36 ?        00:00:00 nginx: worker process
0 S root        2114    2025  0  80   0 -  3087 -      03:37 pts/1    00:00:00 grep --color=auto nginx

7.5 事件相关的配置: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@Nginx ~]# 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@Nginx ~]# ab -n 30000 http://192.168.25.147/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.25.147 (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个并发请求

7.6 网络连接相关的配置参数

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:	client_body_timeout time;
Default: client_body_timeout 60s;
Context: http, server,location

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

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

7.7 fastcgi的相关配置参数

LNMP: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;
        }

7.8 常需要进行调整的参数

worker_processes        //进程数量
worker_connections      //单个进程能够打开的连接数的数量
worker_cpu_affinity     //cpu核心的绑定
worker_priority         //进程的优先级

7.9 nginx作为web服务器时使用的配置

7.9.1 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;
    }
  }
}

7.9.2 http{}段配置指令

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

......
    server{
        listen       81;
        server_name  www.jj.com;

        location / {
            root html/test;
            index index.html;
       }
    }
 ......
 
[root@Nginx ~]# cd /usr/local/nginx/html/
[root@Nginx html]# ls
50x.html  index.html
[root@Nginx html]# mkdir test
[root@Nginx html]# ls
50x.html  index.html  test
[root@Nginx html]# echo 'jjyy' > test/index.html
[root@Nginx html]# nginx -s stop;nginx


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

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

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

在这里插入图片描述
root path; :设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径(默认路径)

location / {
            root   html;
            index  index.html index.htm;
        }

alias path; :用于location配置段,定义路径别名

[root@Nginx ~]# mkdir -p /var/www/html
[root@Nginx ~]# chown -R nginx.nginx /var/www/html/
[root@Nginx ~]# echo 'yykk' > /var/www/html/index.html

location / {
            alias   /var/www/html/;      //路径要写绝对路径
            index  index.html index.htm;
        }


root path;和alias path;设置的区别
	root path方式设置location表示最终访问的资源地址是root path指定的位置+location后面的URI
	alias方式设置表示最终访问的资源地址是alias后面跟的路径

在这里插入图片描述
index file; 默认主页面

location / {
            root   html;
            index  index.html index.htm;    //网页默认访问主页面
        }

location / {
            root   html;
            index test  index.html index.htm;    //自定义网页默认访问页面
        }

在这里插入图片描述
error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面

location / {
            root    html;
            index   index.html index.htm;
        }

        error_page  404              /404.html;    //此字段应该写在server字段中,而不是location字段中

[root@Nginx html]# ls
404.html  50x.html  index.html
[root@Nginx html]# cat 404.html 
jjyy

在这里插入图片描述
[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码

location / {
            root    html;
            index   index.html index.htm;
        }

        error_page  404 =200              /404.html;

在这里插入图片描述
log_format :定义日志格式

                    #远程主机地址   #远程主机的用户 #本地时间       #请求资源的方法
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;			#此处的main可以是任意,但是要和上面的log_format后面的对应

//注意:此处可用变量为nginx各模块内建变量,访问日志是在http中配置受影响的是整个网站

[root@Nginx ~]# ls /usr/local/nginx/logs/
access.log  error.log  nginx.pid

[root@Nginx logs]# tail -f access.log     //访问日志
192.168.25.1 - - [27/Oct/2021:01:34:17 -0400] "GET /test/ HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" "-"

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

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

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明

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

  location /test {
      echo "test";
  }
}

//以上写法可以匹配到
[root@localhost ~]# curl http://192.168.25.147/test
test
[root@localhost ~]# curl http://192.168.25.147/test?.,kadad
test
[root@localhost ~]# curl http://192.168.25.147/test/
test
[root@localhost ~]# curl http://192.168.25.147/test/sasa
test


// =: 表示必须与指定的模式精确匹配
  location = /test {
      echo "yy";
  }
}


//以上写法可以匹配到
[root@localhost ~]# curl http://192.168.25.147/test
yy
[root@localhost ~]# curl http://192.168.25.147/test?p2
yy

//以下内容无法匹配
[root@localhost ~]# curl http://192.168.25.147/test/
test
[root@localhost ~]# curl http://192.168.25.147/test/?p2
test


// ~: 表示指定的正则表达式要区分大小写
  location ~ ^/test$ {
     echo  "jj";
  }
}


//以上写法可以匹配
[root@localhost ~]# curl http://192.168.25.147/test
jj
[root@localhost ~]# curl http://192.168.25.147/test?p2
jj


//以下内容无法匹配
[root@localhost ~]# curl http://192.168.25.147/test/

[root@localhost ~]# curl http://192.168.25.147/testD
test
[root@localhost ~]# curl http://192.168.25.147/Test

// ~*: 表示指定的正则表达式不区分大小写
server {
  server_name www.example.com;
  location ~* ^/test$ {
      echo "tt";
  }
}


//以上写法可以匹配到
[root@localhost ~]# curl http://192.168.25.147/test
tt
[root@localhost ~]# curl http://192.168.25.147/test?DAS
tt
[root@localhost ~]# curl http://192.168.25.147/TEST
tt
//以下内容无法匹配
[root@localhost ~]# curl http://192.168.25.147/test/
[root@localhost ~]# curl http://192.168.25.147/testfa

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

查找顺序和优先级:由高到底依次为

  • 带有=的精确匹配优先
  • 正则表达式按照他们在配置文件中定义的顺序
  • 带有~^修饰符的,开头匹配
  • 带有~ 或~*修饰符的,如果正则表达式与URI匹配
  • 没有修饰符的精确匹配
//优先级次序如下
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

7.10 Nginx平滑升级

7.10.1 平滑升级过程

  1. 获取现有的程序编译的参数
  2. 获取新版本的软件包或功能包
  3. 将新功能或新版本进行编译
  4. 备份原程序
  5. 替换原程序

7.10.2升级

//首先查看已经安装的Nginx的编译参数
[root@Nginx ~]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --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 ~]# dnf -y install unzip
[root@Nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-master.zip

//解压新模块包和nginx的包
[root@Nginx ~]# unzip echo-nginx-module-master.zip 
[root@Nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-master  echo-nginx-module-master.zip
[root@Nginx ~]# ls echo-nginx-module-master
config  LICENSE  README.markdown  src  t  util  valgrind.suppress
[root@Nginx src]# tar xf nginx-1.20.1.tar.gz 
[root@Nginx src]# ls
debug  kernels  nginx-1.20.1  nginx-1.20.1.tar.gz

//重新编译nginx
[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 --add-module=/root/echo-nginx-module-master

//执行make,不要执行make install,如果执行了make install则会把之前的nginx配置覆盖
[root@Nginx nginx-1.20.1]# make

//执行完上一步操作后,可以发现在当前目录的objs目录中生生成一个nginx的主程序文件
[root@Nginx nginx-1.20.1]# ls objs/
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src

//新旧程序对比
[root@Nginx nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx 
-rwxr-xr-x  1 root root 6831128 10月 27 02:11 objs/nginx
-rwxr-xr-x. 1 root root 6308640 10月 24 23:50 /usr/local/nginx/sbin/nginx

//备份原有的nginx主程序文件
[root@Nginx ~]# cp /usr/local/nginx/sbin/nginx /opt/
[root@Nginx ~]# ls /opt/
mime.types  nginx  nginx.conf

//停止旧程序使用新程序启动使用旧配置文件
[root@Nginx ~]# nginx -s stop;/usr/src/nginx-1.20.1/objs/nginx -c /usr/local/nginx/conf/nginx.conf
[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               [::]:*              
[root@Nginx ~]# ps -ef | grep nginx
root        1931    1539  0 01:09 pts/0    00:00:00 mv -i index.html /usr/localnginx/html/
root        5462       1  0 02:17 ?        00:00:00 nginx: master process /usr/src/nginx-1.20.1/objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx       5463    5462  0 02:17 ?        00:00:00 nginx: worker process
nginx       5464    5462  0 02:17 ?        00:00:00 nginx: worker process
nginx       5465    5462  0 02:17 ?        00:00:00 nginx: worker process
root        5468    1539  0 02:17 pts/0    00:00:00 grep --color=auto nginx

//测试新功能是否有效
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location / {
            root    html;
            index   index.html index.htm;
        }

        location /test {
            echo "jjyy";
        }
......

[root@Nginx ~]# /usr/src/nginx-1.20.1/objs/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@Nginx ~]# /usr/src/nginx-1.20.1/objs/nginx -s reload

[root@Nginx ~]# curl http://192.168.25.147/test
jjyy

//用新程序替换旧程序
[root@Nginx ~]# cp /usr/src/nginx-1.20.1/objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y

[root@Nginx ~]# /usr/src/nginx-1.20.1/objs/nginx -s stop;nginx
[root@Nginx ~]# ps -ef | grep nginx
root        1931    1539  0 01:09 pts/0    00:00:00 mv -i index.html /usr/localnginx/html/
root        5495       1  0 02:27 ?        00:00:00 nginx: master process nginx
nginx       5496    5495  0 02:27 ?        00:00:00 nginx: worker process
nginx       5497    5495  0 02:27 ?        00:00:00 nginx: worker process
nginx       5498    5495  0 02:27 ?        00:00:00 nginx: worker process
root        5502    1539  0 02:27 pts/0    00:00:00 grep --color=auto nginx

//到此升级完毕

7.11访问控制

一般用于location段,也可以用于server字段,此时就对当前server字段中的所有location生效,也可以用于http字段,此时就对当前http字段中的所有server字段生效

//用法
allow:白名单,设定允许哪台或哪些主机访问
deny:黑名单,设定禁止哪台或哪些主机访问

location / {
            root html;
            index index.html;
            deny all;      //拒绝所以IP访问
        }

在这里插入图片描述

location / {
            root html;
            index index.html;
            allow 192.168.25.147;    //表示只允许本机访问,拒绝其他所有主机访问
            deny all;
        }

[root@Nginx ~]# curl 192.168.25.147
<!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>
[root@Nginx ~]# hostname -I
192.168.25.147 

7.12 基于用户认证

用户认证和访问控制字段类似此字段写的位置会影响其生效的范围

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

//user_auth_file内容格式为:
username:password

//生成密码文件
[root@Nginx ~]# htpasswd -c -m /usr/local/nginx/conf/.passwd tom      #这里的文件建议用隐藏文件,最后的用户为虚拟用户
New password: 
Re-type new password: 
Adding password for user tom
[root@Nginx ~]# cat /usr/local/nginx/conf/.passwd 
tom:$apr1$oEiLUGlg$CUs9Rg3nSnvTg0lOaKXyX/


[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
       location /test {
            root html;
            index index.html;
            auth_basic "飞飞大SB";
            auth_basic_user_file ".passwd";

        }

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

7.13 https配置

生成私钥,生成证书签署请求并获得证书,然后再nginx.conf中配置如下内容

生成证书

//创建密钥存放目录
[root@Nginx ~]# mkdir -p /etc/pki/CA
[root@Nginx ~]# cd /etc/pki/CA
[root@Nginx CA]# mkdir private

//生成私钥
[root@Nginx CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)     //生成密钥,括号必须要
Generating RSA private key, 2048 bit long modulus (2 primes)
.....+++++
........................+++++
e is 65537 (0x010001)
[root@Nginx CA]# ls private/
cakey.pem

//CA生成自签名证书
[root@Nginx CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
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) []:HB    //省份的名字
Locality Name (eg, city) [Default City]:WH    //城市的名字
Organization Name (eg, company) [Default Company Ltd]:runtime        //公司的域名
Organizational Unit Name (eg, section) []:runtime     //单位的名字
Common Name (eg, your name or your server's hostname) []:www.jj.com    //主机的名字
Email Address []:1@2.com    //邮箱

//在CA目录下创建certs newcerts crl目录,并生成序列号
[root@Nginx CA]# ls
cacert.pem  private
[root@Nginx CA]# mkdir certs newcerts crl
[root@Nginx CA]# ls
cacert.pem  certs  crl  newcerts  private
[root@Nginx CA]# touch index.txt && echo 01 > serial
[root@Nginx CA]# ls
cacert.pem  certs  crl  index.txt  newcerts  private  serial

//创建证书存放目录
[root@Nginx ~]# mkdir /usr/local/nginx/conf/ssl

//生成密钥
[root@Nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
......................................+++++
.+++++
e is 65537 (0x010001)
[root@Nginx ssl]# ls
nginx.key

// 生成证书签署请求
[root@Nginx ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
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]:CH        
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:runtime
Common Name (eg, your name or your server's hostname) []:www.jj.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:    //是否需要给证书设置密码,可以直接回车跳过
An optional company name []:

[root@Nginx ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 27 10:21:49 2021 GMT
            Not After : Oct 27 10:21:49 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = runtime
            commonName                = www.jj.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                89:36:99:05:31:41:2C:86:11:00:22:E4:B9:68:7E:68:44:6F:16:9D
            X509v3 Authority Key Identifier: 
                keyid:E5:88:F3:CB:29:F4:DC:15:23:70:9C:32:81:FA:89:AA:0F:E7:B9:AF

Certificate is to be certified until Oct 27 10:21:49 2022 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

[root@Nginx ssl]# ls
nginx.crt  nginx.csr  nginx.key

//证书生成完毕
    server {
        listen       443 ssl;
        server_name  www.jj.com;

        ssl_certificate      ssl/nginx.crt;        //指定证书位置
        ssl_certificate_key  ssl/nginx.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;
        }
    }

}

在这里插入图片描述

7.14 开启状态界面

要想使用此功能在编译安装时需要指定:–with-http_stub_status_module参数

location /status {
            stub_status on;  
            allow 192.168.25.147/32;    #建议设置访问控制
            deny all;
        }


//访问状态页面的方式:http://server_ip/status
[root@Nginx ~]# curl http://192.168.25.147/status
Active connections: 1 
server accepts handled requests
 38 38 46 
Reading: 0 Writing: 1 Waiting: 0 

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

7.15 使用zabbix监控Nginx的状态页面

zabbix的安装以及配置请参考:监控服务zabbix部署

//在nginx上安装zabbix_agentd
[root@Nginx ~]# cd /usr/src/
[root@Nginx src]# tar xf zabbix-5.4.4.tar.gz 

//安装编译工具和依赖包
[root@Nginx ~]# yum -y install pcre-devel gcc gcc-c++ make

//创建系统账户
[root@Nginx ~]# useradd -r -M -s /sbin/nologin zabbix

//编译安装agent
[root@Nginx zabbix-5.4.4]# ./configure --enable-agent
[root@Nginx zabbix-5.4.4]# make install

//修改agent配置文件/usr/local/etc/zabbix_agentd.conf
[root@Nginx ~]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1				#取消注释并修改值为1
Server=192.168.25.146
ServerActive=192.168.25.146    //服务端IP
Hostname=kzrBnysG

//启动服务
[root@Nginx ~]# zabbix_agentd 
[root@Nginx ~]# ss -antl
State   Recv-Q   Send-Q     Local Address:Port      Peer Address:Port  Process  
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              0.0.0.0:443            0.0.0.0:*              
LISTEN  0        128                 [::]:22                [::]:*       

//在agentd编写脚本
[root@Nginx scripts]# cat status.sh 
#! /bin/bash

case $1 in
    "Reading")
    curl -s http://192.168.25.147/status | awk 'NR==4 {print $2}';;
    "Writing")
    curl -s http://192.168.25.147/status | awk 'NR==4 {print $4}';;
    "Waiting")
    curl -s http://192.168.25.147/status | awk 'NR==4 {print $6}'
esac

//修改/usr/local/etc/zabbix_agentd.conf
[root@Nginx ~]# vim /usr/local/etc/zabbix_agentd.conf
UserParameter=check_status[*],/bin/bash /scripts/status.sh $1

//重启agentd端的zabbix服务
[root@Nginx ~]# pkill zabbix_agentd
[root@Nginx ~]# zabbix_agentd 

//在zabbix服务器上测试key键值是否有效
[root@localhost ~]# zabbix_get -s 192.168.25.147 -k check_status[Writing]
1

添加主机
在这里插入图片描述

添加监控项
在这里插入图片描述
添加动作
在这里插入图片描述
告警信息
在这里插入图片描述
其余两个监控项和上面一样添加即可
在这里插入图片描述

7.16 rewrite

  • rewrite是用来重写URL的
  • rewrite的特点
    • 不改变用户的访问方式
    • 通过规则重新URL

语法:rewrite regex replacement flag;

//示例:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
此处的$1用于引用(.*.jpg)匹配到的内容,又如

rewrite ^/bbs/(.*)$ http://www.example.com/index.html redirect;
如上例所示,replacement可以是某个路径,也可以是某个URL



//创建一个项目,然后访问
[root@Nginx test]# ls
1.jpg
[root@Nginx test]# pwd
/usr/local/nginx/html/test


        location / {
            root html;
            index index.html;
        }

在这里插入图片描述

//修改项目的名字
[root@Nginx html]# mv test/ tests
[root@Nginx html]# ls
50x.html  index.html  tests

//此时再次访问资源,发现无法访问

在这里插入图片描述

//修改配置文件,配置rewrite
        location / {
            root html;
            index index.html;
        }

        location /test {
            rewrite ^/test/(.*\.jpg)$ /tests/$1 break;    #break 本条规则匹配完成即终止,不再匹配后面的任何规则
        }

//重载配置文件后再次访问

在这里插入图片描述
常见的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
//last示例
        location /test {
            rewrite ^/test/(.*\.jpg)$ /tests/$1 last;
        }

        location /tests {
            rewrite ^/tests/(.*\.jpg)$ http://www.baidu.com last;    last 本条规则匹配完成后,继续向下匹配新的location URI规则
        }

在这里插入图片描述
浏览器访问,发现访问到第二条规则的页面

//last和break组合使用示例
location /test {
            rewrite ^/test/(.*\.jpg)$ /tests/$1 break;    #break 本条规则匹配完成即终止,不再匹配后面的任何规则
        }

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

在这里插入图片描述
浏览器访问,发现访问到第一条规则的页面

//redirect示例
location /test {
            rewrite ^/test/(.*\.jpg)$ https://cn.bing.com/images/search?view=detailV2&ccid=vWLmxpFe&id=E9EBB16AF03E7C025F7C5028B8BA355F580C5484&thid=OIP.vWLmxpFeQqrozvZAxm-OnQHaEK&mediaurl=https%3a%2f%2fup.enterdesk.com%2fedpic%2f3a%2ff9%2fd7%2f3af9d70258a17d0e58f461b9e4790072.jpg&exph=576&expw=1024&q=%e5%88%98%e4%ba%a6%e8%8f%b2%e5%a3%81%e7%ba%b8%e7%94%b5%e8%84%91%e6%a1%8c%e9%9d%a24k&simid=608025974657665709&FORM=IRPRST&ck=7D46923C0A4A7BBDF2B680D49AE6C18B&selectedIndex=505&ajaxhist=0&ajaxserp=0 redirect;    #redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
        }

在这里插入图片描述

  • rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)
  • nginx使用的语法源于Perl兼容正则表达式(PCRE)库
标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
l匹配 l之前或之后的实体
()分组,组成一组用于匹配的实体,通常会有

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

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

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

7.17 if

语法:if (condition) {...}
应用的字段: server段  location段

常见的condition

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

7.17.1 基于浏览器实现分离案例

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;
}

7.17.2 防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

7.18 反向代理与负载均衡

  • nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力
  • nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了
  • 但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储
  • Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache
  • 如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:./configure --add-module=../ngx_cache_purge-1.0 .....
  • nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如
upstream idfsoft.com {							#此字段要写在server字段的前面
  ip_hash;
  server 127.0.0.1:9080 weight=5;				
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}


 upstream webservers{
        server 192.168.25.146 weight=3;    #weight表示访问三次146后访问一次148
        server 192.168.25.148;

    }

注:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,翻墙等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。
  • 定义好upstream后,需要在server段内添加如下内容:
server {
  location / {
    proxy_pass http://webservers;				#这里要和upstream段配置的域名一致
  }
}

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

环境说明

主机IP服务
LB192.168.25.147nginx
RS1192.168.25.146apache
RS2192.168.25.148lnmp

首先安装后端服务器上的服务

  • RS1上安装apache
//安装开发工具包
[root@RS1 ~]# yum groups mark install 'Development Tools' -y
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:07:41 前,执行于 2021年09月23日 星期四 02时03分01秒。
依赖关系解决。
==============================================================================
 软件包            架构             版本              仓库               大小
==============================================================================
安装组:
 Development Tools                                                           

事务概要
==============================================================================

完毕!
......

//创建apache服务的用户和组
[root@RS1 ~]# useradd -r -M -s /sbin/nologin apache
[root@RS1 ~]# id apache 
uid=975(apache) gid=973(apache) 组=973(apache)
[root@RS1 ~]# 

//安装依赖包
[root@RS1 ~]# yum -y install openssl-devel pcre-devel expat-devel libtool gcc gcc-c++ make
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:11:00 前,执行于 2021年09月23日 星期四 02时03分01秒。
依赖关系解决。
......

///下载并解压软件包apr,apr-util,httpd
[root@RS1 src]# ls
apr-1.7.0.tar.gz  apr-util-1.6.1.tar.gz  debug  httpd-2.4.48.tar.gz  kernels
[root@RS1 src]# tar xf apr-1.7.0.tar.gz 
[root@RS1 src]# tar xf apr-util-1.6.1.tar.gz 
[root@RS1 src]# tar xf httpd-2.4.48.tar.gz 
[root@RS1 src]# ls
apr-1.7.0         apr-util-1.6.1         debug         httpd-2.4.48.tar.gz
apr-1.7.0.tar.gz  apr-util-1.6.1.tar.gz  httpd-2.4.48  kernels

//编译安装apr
[root@RS1 src]# cd apr-1.7.0/
[root@RS1 apr-1.7.0]# vim configure
       cfgfile="${ofile}T"
       trap "$RM \"$cfgfile\"; exit 1" 1 2 15
        $RM "$cfgfile"        //将此行加上注释,或者删除此行

[root@RS1 apr-1.7.0]# ./configure --prefix=/usr/local/apr
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
Configuring APR library
Platform: x86_64-pc-linux-gnu
checking for working mkdir -p... yes
......

[root@RS1 apr-1.7.0]# make && make install
make[1]: 进入目录“/usr/src/apr-1.7.0”
/bin/sh /usr/src/apr-1.7.0/libtool --silent --mode=compile gcc -g -O2 -pthread   -DHAVE_CONFIG_H  -DLINUX -D_REENTRANT -D_GNU_SOURCE   -I./include -I/usr/src/apr-1.7.0/include/arch/unix -I./include/arch/unix -I/usr/src/apr-1.7.0/include/arch/unix -I/usr/src/apr-1.7.0/include -I/usr/src/apr-1.7.0/include/private -I/usr/src/apr-1.7.0/include/private  -o encoding/apr_encode.lo -c encoding/apr_encode.c && touch encoding/apr_encode.lo
/usr/src/apr-1.7.0/build/mkdir.sh tools
......

//编译安装apr-util
[root@RS1 src]# cd apr-util-1.6.1/
[root@RS1 apr-util-1.6.1]# ./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for a BSD-compatible install... /usr/bin/install -c
......

[root@RS1 apr-util-1.6.1]# make && make install
make[1]: 进入目录“/usr/src/apr-util-1.6.1”
/bin/sh /usr/local/apr/build-1/libtool --silent --mode=compile gcc -g -O2 -pthread   -DHAVE_CONFIG_H  -DLINUX -D_REENTRANT -D_GNU_SOURCE   -I/usr/src/apr-util-1.6.1/include -I/usr/src/apr-util-1.6.1/include/private  -I/usr/local/apr/include/apr-1    -o buckets/apr_brigade.lo -c buckets/apr_brigade.c && touch buckets/apr_brigade.lo
......

//编译安装httpd
[root@RS1 httpd-2.4.48]# ./configure --prefix=/usr/local/apache \
> --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
checking for chosen layout... Apache
checking for working mkdir -p... yes
checking for grep that handles long lines and -e... /usr/bin/grep
......

[root@RS1 httpd-2.4.48]# make && make install
....

//安装后配置
[root@RS1 ~]# ls /usr/local/
apache  apr-util  etc    include  lib64    sbin   src
apr     bin       games  lib      libexec  share
[root@RS1 ~]# ls /usr/local/apache/
bin    cgi-bin  error   icons    logs  manual
build  conf     htdocs  include  man   modules
[root@RS1 ~]# echo 'export PATH=/usr/local/apache/bin:$PATH' > /etc/profile.d/httpd.sh  //配置环境变量
[root@RS1 ~]# source /etc/profile.d/httpd.sh
[root@RS1 ~]# which httpd
/usr/local/apache/bin/httpd

[root@RS1 ~]# ls /usr/local/apache/
bin    cgi-bin  error   icons    logs  manual
build  conf     htdocs  include  man   modules
[root@RS1 ~]# ln -s /usr/local/apache/include/ /usr/include/httpd
[root@RS1 ~]# ll /usr/include/
-rw-r--r--.  1 root root    181 2月  19 2020 gssapi.h
drwxr-xr-x.  2 root root    268 9月  23 02:14 gssrpc
lrwxrwxrwx.  1 root root     26 9月  23 02:50 httpd -> /usr/local/apache/include/
-rw-r--r--.  1 root root   1857 1月  16 2020 iconv.h

[root@RS1 ~]# vim /etc/man_db.conf
  #MANDATORY_MANPATH                      /usr/src/pvm3/man
#
MANDATORY_MANPATH                       /usr/man
MANDATORY_MANPATH                       /usr/share/man
MANDATORY_MANPATH                       /usr/local/share/man
MANDATORY_MANPATH                       /usr/local/apache/man  //帮助文档
#---------------------------------------------------------
# set up PATH to MANPATH mapping
......

//取消配置文件中ServerName前面的注释
[root@RS1 ~]# vim /usr/local/apache/conf/httpd.conf
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName www.example.com:80

#
......

//启动httpd
[root@RS1 ~]# apachectl start
[root@RS1 ~]# ss -antl
State      Recv-Q     Send-Q         Local Address:Port           Peer Address:Port     
LISTEN     0          128                  0.0.0.0:111                 0.0.0.0:*        
LISTEN     0          32             192.168.122.1:53                  0.0.0.0:*        
LISTEN     0          128                  0.0.0.0:22                  0.0.0.0:*        
LISTEN     0          5                  127.0.0.1:631                 0.0.0.0:*        
LISTEN     0          128                127.0.0.1:6010                0.0.0.0:*        
LISTEN     0          128                127.0.0.1:6011                0.0.0.0:*        
LISTEN     0          128                     [::]:111                    [::]:*        
LISTEN     0          128                        *:80                        *:*        
LISTEN     0          128                     [::]:22                     [::]:*        
LISTEN     0          5                      [::1]:631                    [::]:*        
LISTEN     0          128                    [::1]:6010                   [::]:*        
LISTEN     0          128                    [::1]:6011                   [::]:*      


//关闭防火墙访问
[root@RS1 ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@RS1 ~]# setenforce 0

在RS1上测试是否能够访问到apache页面
在这里插入图片描述

  • RS2上安装lnmp
  1. 安装Nginx
//创建系统用户nginx
[root@RS2 ~]# useradd -r -M -s /sbin/nologin nginx

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

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

//编译安装nginx
[root@RS2 ~]# cd /usr/src/
[root@RS2 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@RS2 src]# tar xf nginx-1.20.1.tar.gz 
[root@RS2 src]# cd nginx-1.20.1
[root@RS2 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@RS2 ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@RS2 ~]# source /etc/profile.d/nginx.sh

//启动nginx
[root@RS2 ~]# /usr/local/nginx/sbin/nginx     //默认启动文件
[root@RS2 ~]# 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               [::]:*         

  1. 安装mysql数据库
//安装依赖包
[root@RS2 ~]# yum -y install ncurses-devel openssl-devel openssl cmake mariadb-devel ncurses-compat-libs

//创建用户和组
[root@RS2 ~]# useradd -r -M -s /sbin/nologin mysql

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

//添加环境变量
[root@RS2 ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@RS2 ~]# source /etc/profile.d/mysql.sh
[root@RS2 ~]# echo $PATH 
/usr/local/mysql/bin:/usr/local/nginx/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

//头文件软连接
[root@RS2 ~]# ln -s /usr/local/mysql/include /usr/include/mysql

//帮助文档
[root@RS2 ~]# vim /etc/man_db.conf
MANDATORY_MANPATH                       /usr/local/mysql/man

//库文件
[root@RS2 ~]# vim /etc/ld.so.conf.d/mysql.conf
/usr/local/mysql/lib
[root@RS2 ~]# ldconfig 

//建立数据存放目录
[root@RS2 ~]# mkdir -p /opt/data
[root@RS2 ~]# chown -R mysql.mysql /opt/data/
[root@RS2 ~]# ll /opt/
总用量 0
drwxr-xr-x. 2 mysql mysql 6 10月 26 01:02 data

//初始化数据库
[root@RS2 ~]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --datadir=/data

//生成配置文件
[root@RS2 ~]# 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@RS2 ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /usr/local/mysql/support-files/mysql.server 
[root@RS2 ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /usr/local/mysql/support-files/mysql.server
[root@RS2 ~]# 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@RS2 ~]# systemctl daemon-reload 
[root@RS2 ~]# systemctl enable --now mysqld
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@RS2 ~]# 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)

  1. 安装PHP
//先下载epel源
[root@RS2 ~]# yum -y install epel-release

//下载依赖包
[root@RS2 ~]# 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@RS2 ~]# 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@RS2 ~]# cd /usr/src/
[root@RS2 src]# tar xf php-8.0.10.tar.xz 
[root@RS2 src]# cd php-8.0.10
[root@RS2 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@RS2 php-8.0.10]# make && make install

//设置环境变量
[root@RS2 php-8.0.10]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh
[root@RS2 php-8.0.10]# source /etc/profile.d/php.sh

//配置php-fpm
[root@RS2 php-8.0.10]# cp php.ini-production /etc/php.ini
cp:是否覆盖'/etc/php.ini'? y
[root@RS2 php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@RS2 php-8.0.10]# chmod +x /etc/init.d/php-fpm
[root@RS2 php-8.0.10]# cp /usr/local/php8/etc/php-fpm.conf.default /usr/local/php8/etc/php-fpm.conf
[root@RS2 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@RS2 ~]# service php-fpm start
Starting php-fpm  done
[root@RS2 ~]# 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                *:*    

  1. 配置nginx
//创建php测试页面
[root@RS2 ~]# cat /usr/local/nginx/html/index.php
<?php
    phpinfo();
?>

//配置nginx
[root@RS2 ~]# 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@RS2 ~]# nginx -s reload

在RS2上测试是否能够访问到php动态页面
在这里插入图片描述

  • 在LB上安装nginx
//创建系统用户nginx
[root@LB ~]# useradd -r -M -s /sbin/nologin nginx

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

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

//编译安装nginx
[root@LB ~]# cd /usr/src/
[root@LB 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@LB src]# tar xf nginx-1.20.1.tar.gz 
[root@LB src]# cd nginx-1.20.1
[root@LB 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@LB ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@LB ~]# source /etc/profile.d/nginx.sh

//启动nginx
[root@LB ~]# /usr/local/nginx/sbin/nginx     //默认启动文件
[root@LB ~]# 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               [::]:*         

  1. 在LB上配置负载均衡
[root@LB ~]# vim /usr/local/nginx/conf/nginx.conf
upstream webservers {
        server 192.168.25.146;
        server 192.168.25.148;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://webservers;    #webservers要与上面的upstream后面所跟的一样
        }

在浏览器上访问192.168.25.147
在这里插入图片描述
在这里插入图片描述

  1. 在LB上配置动静分离
[root@LB ~]# vim /usr/local/nginx/conf/nginx.conf
    upstream static {    
        server 192.168.25.146;
    }
    upstream dynamic {
        server 192.168.25.148;
    }

    server {
        listen       80;
        server_name  localhost;

......
        location / {
            proxy_pass http://static;    #访问根目录下的静态资源会自动跳转到192.168.25.146上进行访问
        }
......
        location ~ \.php$ {
            proxy_pass   http://dynamic;    #访问根目录下的.php动态资源会自动跳转到192.168.25.148上进行访问

在浏览器上进行访问测试
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值