nginx

1. nginx简介

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。

nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。

第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

nginx的特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

2. nginx的特性与优点

2.1 nginx的特性

nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

2.2 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,内存映射)等性能优化

3. nginx的功能及应用类别

3.1 nginx的基本功能

  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
    支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL

3.2 nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于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模块从功能上分为三类,分别是:

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

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

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

具体的指令,请参考nginx的官方文档:http://nginx.org/en/docs/ngx_core_module.html

4.2 nginx的工作原理

nginx的模块直接被编译进nginx,因此属于静态编译方式。

启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。

在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个orker线程用来处理n个request
在这里插入图片描述

下图展示了nginx模块一次常规的HTTP请求和响应的过程
在这里插入图片描述
下图展示了基本的WEB服务请求步骤
在这里插入图片描述

1.客户端发起请求,然后与服务端建立tcp连接
2.服务器接收请求
3.进行反向代理,然后服务器处理请求
4.查看访问资源的类型(可能是本地的资源,也可能是通过NFS挂载的资源)
5.构建响应报文
6.通过网络接口返回响应报文给客户端
7.服务端将本次的操作记录到日志中

5. nginx的安装与配置

5.1 nginx的安装

//创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
//安装依赖环境
[root@localhost ~]# yum -y install pcre-devel pcre gcc gcc-c++ openssl-devel zlib zlib-devel make vim wget openssl openssl-devel gd-devel
//创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
//下载nginx
root@localhost ~]# cd /usr/src/
[root@localhost src]# wget https://nginx.org/download/nginx-1.20.1.tar.gz
--2021-10-25 15:43:26--  https://nginx.org/download/nginx-1.20.1.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1061461 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.20.1.tar.gz”

nginx-1.20.1.tar.gz              100%[========================================================>]   1.01M   442KB/s  用时 2.3s    

2021-10-25 15:43:30 (442 KB/s) - 已保存 “nginx-1.20.1.tar.gz” [1061461/1061461])

//编译安装
[root@localhost src]# ls
debug  kernels  nginx-1.20.1.tar.gz
[root@localhost src]# tar xf nginx-1.20.1.tar.gz 
[root@localhost src]# cd nginx-1.20.1/
[root@localhost 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@localhost nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

5.2 nginx安装后配置

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

//启动nginx
[root@localhost nginx-1.20.1]# 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                                 [::]:*              
[root@localhost nginx-1.20.1]# 
//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}
//检查语法
[root@localhost ~]# 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

//查看nginx的版本
[root@localhost ~]# nginx -v
nginx version: nginx/1.20.1
[root@localhost ~]# 

// 查看更加详细的信息
[root@localhost ~]# 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@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# ls
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.default   uwsgi_params
fastcgi.conf.default  koi-utf                 mime.types.default  scgi_params          uwsgi_params.default
fastcgi_params        koi-win                 nginx.conf          scgi_params.default  win-utf
[root@localhost conf]# cp nginx.conf mime.types /opt/
[root@localhost conf]# cd /opt/
[root@localhost opt]# ls
mime.types  nginx.conf
[root@localhost opt]# vim nginx.conf 
 3 worker_processes  1;
[root@localhost opt]# ps -ef|grep nginx
root       24915       1  0 16:00 ?        00:00:00 nginx: master process nginx
nginx      24991   24915  0 16:30 ?        00:00:00 nginx: worker process
nginx      24992   24915  0 16:30 ?        00:00:00 nginx: worker process
nginx      24993   24915  0 16:30 ?        00:00:00 nginx: worker process
root       25030    1501  0 16:39 pts/0    00:00:00 grep --color=auto nginx
[root@localhost opt]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@localhost opt]# ps -ef|grep nginx
root       25038       1  0 16:40 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx      25039   25038  0 16:40 ?        00:00:00 nginx: worker process
root       25041    1501  0 16:40 pts/0    00:00:00 grep --color=auto nginx
[root@localhost opt]# 

 //修改进程
[root@localhost ~]# ps -ef | grep nginx
root       24915       1  0 16:00 ?        00:00:00 nginx: master process nginx
nginx      24916   24915  0 16:00 ?        00:00:00 nginx: worker process
root       24941    1501  0 16:27 pts/0    00:00:00 grep --color=auto nginx
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
3 worker_processes  3;   //修改进程为3

//发送服务控制信号,重新加载配置文件
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ps -ef | grep nginx
root       24915       1  0 16:00 ?        00:00:00 nginx: master process nginx
nginx      24991   24915  0 16:30 ?        00:00:00 nginx: worker process
nginx      24992   24915  0 16:30 ?        00:00:00 nginx: worker process
nginx      24993   24915  0 16:30 ?        00:00:00 nginx: worker process
root       24995    1501  0 16:30 pts/0    00:00:00 grep --color=auto nginx

6 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提供的网站,包括虚拟主机

6.1 nginx.conf配置详解

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

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

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

derective value1 [value2 ...];

支持使用变量

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

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

daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志

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@localhost ~]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@localhost ~]# 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@localhost ~]# vim /opt/nginx.conf 
#user  nobody;
worker_processes  1;

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

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

//查看日志报错
[root@localhost ~]# curl http://192.168.8.130/sx.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@localhost ~]# cat /var/log/nginx/error.log 
2021/10/25 16:30:06 [notice] 24990#0: signal process started
2021/10/25 16:31:54 [emerg] 24997#0: directive "worker_processes" is not terminated by ";" in /usr/local/nginx/conf/nginx.conf:12
2021/10/25 16:40:14 [notice] 25036#0: signal process started
2021/10/25 16:46:41 [notice] 25051#0: signal process started
2021/10/25 16:51:26 [notice] 25132#0: signal process started
"/usr/local/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.8.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.8.130", referrer: "http://192.168.8.130/"
2021/10/25 16:56:08 [notice] 25194#0: signal process started
2021/10/26 09:49:03 [error] 1507#0: *2 open() "/usr/local/nginx/html/sx.txt" failed (2: No such file or directory), client: 192.168.8.130, server: localhost, request: "GET /sx.txt HTTP/1.1", host: "192.168.8.130"

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

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

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

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

就是worker进程最多能打开1024个文件数,最好将值调整至65535最大的值。这个值是因为端口号最多只有65535

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
  2 #user  nobody;
  3 worker_processes  1;
  4 worker_rlimit_nofile 65535;   //修改这一行

//查询worker进程最大文件数
[root@localhost ~]# ulimit -a
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 30996
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024   //查询worker进程最大文件数

//设置系统的支持的访问数量

//文件最后两行添加
[root@localhost ~]# vim /etc/security/limits.conf 
* soft nofile 65535
* hard nofile 65535

[root@localhost ~]# systemctl restart nginx.service 
[root@localhost ~]# ulimit -a | grep -w 65535
open files                      (-n) 65535

6.4 优化性能的配置参数

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核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值

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

什么是上下文切换?
上下文切换就是从当前执行任务切换到另一个任务执行的过程。但是,为了确保下次能从正确的位置继续执行,在切换之前,会保存上一个任务的状态。下一次会接着上一个任务运行退出的地方接着运行。
为了避免上下文切换若你是8核的cpu给7核到nginx进程使用,剩余的给其他系统服务使用。

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

//将进程绑定到某个cpu核心中
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 5 worker_cpu_affinity 0001 0010;  //添加两核

//然后使用top命令,再点击L键,输入nginx就可以找到nginx的进程

在这里插入图片描述
再按f键就会跳到这个页面,按上下左右的下键将光标移至P那一行,点击空格键选中,按q退出就可以看到,nginx进程使用的cpu了,并绑定成功,也不会进行上下文切换了
在这里插入图片描述
worker_priority number; //指明worker进程的nice值

优先级分为两种一个实时优先级,一个相对优先级
能控制的优先级有40个数,-20到19 对应100-139
nice是数字越低优先级越高。
[root@localhost conf]# head -5 nginx.conf

user  nginx nginx;
worker_processes  1;
worker_cpu_affinity 0001 0010;
worker_priority -20;
[root@localhost conf]# systemctl restart nginx.service
使用top命令
11243 nginx      0 -20   77740   2188    640 S   0.0  0.0   0:00.00 nginx 

[root@localhost opt]# ps -elf | grep nginx
1 S root      11242      1  0  80   0 - 19341 sigsus 20:05 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nginx     11243  11242  0  60 -20 - 19435 ep_pol 20:05 ?        00:00:00 nginx: worker process
0 S root      16510   2288  0  80   0 - 28206 pipe_w 20:08 pts/2    00:00:00 grep --c

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

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

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

这是作为压测的工具
[root@localhost conf]# vim nginx.conf
14 events {
 15     worker_connections  20480;

[root@localhost conf]# systemctl restart nginx.service
若没有ab命令就请安装httpd-tools包组
[root@localhost conf]# yum -y install httpd-tools
-c 用于指定的并发数;-n 用于指定压力测试总共的执行次数
[root@localhost conf]# ab -c 100 -n 5000 http://192.168.182.131/index1.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.182.131 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests


Server Software:        nginx/1.20.1
Server Hostname:        192.168.182.131
Server Port:            80

Document Path:          /index1.html
Document Length:        153 bytes

Concurrency Level:      100
Time taken for tests:   0.390 seconds
Complete requests:      5000
Failed requests:        0
Write errors:           0
Non-2xx responses:      5000
Total transferred:      1515000 bytes
HTML transferred:       765000 bytes
Requests per second:    12825.64 [#/sec] (mean)
Time per request:       7.797 [ms] (mean)
Time per request:       0.078 [ms] (mean, across all concurrent requests)
Transfer rate:          3795.09 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    3   2.4      3      35
Processing:     1    5   5.3      3      49
Waiting:        0    4   4.9      3      47
Total:          3    8   6.0      6      52

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      7
  75%      8
  80%      8
  90%     11
  95%     15
  98%     20
  99%     49
 100%     52 (longest request)

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

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长
keepalive_timeout number //65s内没做任何操作就超时退出
keepalive_requests number //连接建立之后可以设置一个值,这个值就是要处理的请求,当请求全部处理完成之后才退出
keepalive_disable [msie6|safari|none]  //disabl可以在http,server,location中配置,在什么地方配置就对哪个地方生效(也就是禁用某个浏览器的长连接),这里的msie6|safari是浏览器的类型,none就是空任何类型都可以访问

[root@localhost conf]# vim nginx.conf
34     keepalive_disable msie6;

tcp_nodelay on|off  //设置使用长连接没有延迟,默认也是no

6.7 fastcgi的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:

location ~ \.php$ {
  root html;
  fastcgi_pass 127.0.0.1:9000;      //定义反向代理
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include fastcgi_params;
}

6.8 常需要进行调整的参数

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

6.9 nginx作为web服务器时使用的配置: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 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口

listen address[:port];
listen port;

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

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

root path; 设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径

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

index file; 默认主页面

index index.php index.html;

error_page code [...] [=code] URI | @name根据http响应状态码来指明特用的错误页面,例如error_page 404 /404_customed.html

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.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;

//注意:此处可用变量为nginx各模块内建变量
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 5 error_log  logs/error.log;   //取消注释打开错误日志

 //取消下面注释打开访问日志
 21     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 22                       '$status $body_bytes_sent "$http_referer" '
 23                       '"$http_user_agent" "$http_x_forwarded_for"';
 24 
 25     access_log  logs/access.log  main;
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# ls /usr/local/nginx/logs/
nginx.pid
[root@localhost ~]# systemctl restart nginx.service 
[root@localhost ~]# ls /usr/local/nginx/logs/
access.log  error.log  nginx.pid
[root@localhost ~]# 

//部署一个http的页面
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# cd test/
[root@localhost test]# vim index.html
[root@localhost test]# cat index.html 
hello world
[root@localhost test]# 

//修改nginx配置文件
[root@localhost test]# vim /usr/local/nginx/conf/nginx.conf
//添加下面几行
 36     server {
 37         listen 82;
 38         server_name test.example.com;
 39 
 40         location / {
 41             root html/test;
 42             index index.html;
 43         }
 44      }

[root@localhost test]# systemctl restart nginx.service 
[root@localhost test]# curl 192.168.8.137:82
hello world
[root@localhost test]# 

root path;设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径

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

index file; 默认主页面
index index.php index.html;

//为了安全可以通过root path;设置资源路径映射
[root@localhost test]# vim /usr/local/nginx/conf/nginx.conf
 55             alias   /var/www/html/;   //alias的特点是的必须跟上绝对路径

[root@localhost test]# mkdir -p /var/www/html
[root@localhost test]# mv /usr/local/nginx/html/test /var/www/html/
[root@localhost test]# ls /var/www/html/
test
[root@localhost test]# systemctl restart nginx.service 
[root@localhost test]# curl 192.168.8.137/test/
hello world
[root@localhost test]# 

错误页面配置

访问一个不存在的页面
在这里插入图片描述

//修改配置文件
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
 48         error_page  404              /404.html;   //取消注释

//发生了错误页面将访问这个页面
[root@localhost ~]# cat /usr/local/nginx/html/404.html 
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# 
[root@localhost ~]# systemctl restart nginx.service 

在这里插入图片描述

平滑升级:

  1. 获取现有的程序编译的参数 -V
  2. 获取新版本的软件包或功能包
  3. 将新功能或新版本进行编译
  4. 备份源程序
  5. 替换原程序
//获取现有的程序编译的参数 -V
[root@localhost ~]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.4.1 20200928 (Red Hat 8.4.1-1) (GCC) 
built with OpenSSL 1.1.1g FIPS  21 Apr 2020
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@localhost ~]# 
//下载一个功能包
[root@localhost ~]# cd /usr/src/
[root@localhost src]# ls
debug  echo-nginx-module-master.zip  kernels
[root@localhost src]# yum -y install unzip
[root@localhost src]# unzip echo-nginx-module-master.zip 
[root@localhost src]# ls
debug  echo-nginx-module-master  echo-nginx-module-master.zip  kernels
[root@localhost src]# 
//将新功能或新版本进行编译
[root@localhost ~]# cd /usr/local/nginx-1.20.1/
[root@localhost 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=/usr/src/echo-nginx-module-master
[root@localhost nginx-1.20.1]# make
[root@localhost nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx 
-rwxr-xr-x 1 root root 6830104 1027 15:44 objs/nginx
-rwxr-xr-x 1 root root 6307584 1027 15:00 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.20.1]# 
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost nginx-1.20.1]# ls /opt/
nginx
[root@localhost nginx-1.20.1]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.20.1]# ps -ef | grep nginx
root       28911       1  0 15:49 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx      28912   28911  0 15:49 ?        00:00:00 nginx: worker process
root       28920   25130  0 15:50 pts/0    00:00:00 grep --color=auto nginx
[root@localhost nginx-1.20.1]# 

//测试新功能
[root@localhost nginx-1.20.1]# vim /usr/local/nginx/conf/nginx.conf
//添加下面几行
 48         location /test {
 49             echo "test";
 50         }
[root@localhost 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@localhost nginx-1.20.1]# objs/nginx -s reload
[root@localhost nginx-1.20.1]# 
[root@localhost nginx-1.20.1]# curl 192.168.8.137/test
test
[root@localhost nginx-1.20.1]# 
//覆盖原程序
[root@localhost nginx-1.20.1]# cp objs/nginx /usr/local/nginx/sbin/nginx 
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y
[root@localhost nginx-1.20.1]# 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@localhost nginx-1.20.1]# objs/nginx -s stop;nginx 
[root@localhost nginx-1.20.1]# ps -ef|grep nginx
root       29039       1  0 16:05 ?        00:00:00 nginx: master process nginx
nginx      29040   29039  0 16:05 ?        00:00:00 nginx: worker process
root       29044   25130  0 16:05 pts/0    00:00:00 grep --color=auto nginx
[root@localhost nginx-1.20.1]# 

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

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

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

常用修饰符说明:

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

没有修饰符表示必须以指定模式开始,如:

       location /test {
            echo "test";
        }

那么如下内容就可正确匹配:

[root@localhost ~]# curl 192.168.8.137/test
test
[root@localhost ~]# curl 192.168.8.137/test/
test
[root@localhost ~]# curl 192.168.8.137/testabc
test
[root@localhost ~]# 

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


         location = /testa {
            echo "test2";
        }

那么如下内容就可正确匹配:

[root@localhost ~]# curl 192.168.8.137/testa
test2
[root@localhost ~]# curl 192.168.8.137/testa?abc
test2

如下内容则无法匹配:

[root@localhost ~]# curl 192.168.8.137/testa/
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# curl 192.168.8.137/testa/testabcd
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# 

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

abc
  location ~ ^/abc$ {
              echo "abc";
          }

那么如下内容就可正确匹配:

[root@localhost ~]# curl 192.168.8.137/abc
abc
[root@localhost ~]# curl 192.168.8.137/abc?abc
abc

如下内容则无法匹配:

[root@localhost ~]# curl 192.168.8.137/abc/
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# curl 192.168.8.137/ABC/
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# curl 192.168.8.137/abcde
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# 

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

       location ~* ^/abc$ {
            echo "abc";
        }

那么如下内容就可正确匹配:

[root@localhost ~]# curl 192.168.8.137/abc
abc
[root@localhost ~]# curl 192.168.8.137/ABC
abc
[root@localhost ~]# curl 192.168.8.137/abc?ABC
abc

如下内容则无法匹配:

[root@localhost ~]# curl 192.168.8.137/abc/
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# curl 192.168.8.137/abccdf
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# 

 43         location = / {
 44             echo "[ configuration A ]";
 45         }
 46 
 47         location / {
 48             echo "[ configuration B ]";
 49         }
 50 
 51         location /documents/ {
 52             echo "[ configuration C ]";
 53         }
 54 
 55         location ^~ /images/ {
 56             echo "[ configuration D ]";
 57         }
 58 
 59         location ~* \.(gif|jpg|jpeg)$ {
 60             echo "[ configuration E ]";
 61         }

[root@localhost ~]# curl http://192.168.8.137
[ configuration A ]
[root@localhost ~]# curl http://192.168.8.137/index.html
[ configuration B ]
[root@localhost ~]# curl http://192.168.8.137/documents/document.html
[ configuration C ]
[root@localhost ~]# curl http://192.168.8.137/images/1.gif
[ configuration D ]
[root@localhost ~]# curl http://192.168.8.137/documents/1.jpg
[ configuration E ]

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

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

  1. 带有=的精确匹配优先
  2. 正则表达式按照他们在配置文件中定义的顺序
  3. 带有^~修饰符的,开头匹配
  4. 带有~~*修饰符的,如果正则表达式与URI匹配
  5. 没有修饰符的精确匹配

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

6.10 访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用多个allow
deny:设定禁止哪台或哪些主机访问,多个参数间用多个deny

//示例
location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16
    allow 2001:0db8::/32;
    deny  all;
//拒绝192.168.8.1访问
      location / {
            deny   192.168.8.1;
            root   html;
            index  index.html index.htm;

        }

在这里插入图片描述

//本地是可以访问的
[root@localhost ~]# curl 192.168.8.137
<!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@localhost ~]# 

//允许192.168.8.1访问,拒绝所有
      location / {
            allow  192.168.8.1;
            deny   all;
            root   html;
            index  index.html index.htm;

        }

在这里插入图片描述

[root@localhost ~]# curl 192.168.8.137
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# 

6.11 基于用户认证

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

user_auth_file内容格式为:

username:password
[root@localhost ~]# yum -y install httpd-tools
[root@localhost ~]# which htpasswd 
/usr/bin/htpasswd
[root@localhost ~]# 

//-c 生成  -m 指定位置
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass admin
New password: admin   //输入密码
Re-type new password: admin   //再次确认
Adding password for user admin
[root@localhost ~]# 
[root@localhost ~]# cat /usr/local/nginx/conf/.pass
admin:$apr1$NbuixWmU$iv9aH8N8CxB95LFc2iI0c1
[root@localhost ~]# 

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 43         location / {
 44             auth_basic "welcome";   //添加这一行
 45             auth_basic_user_file "conf/.pass";   //添加这一行
 46             root   html;
 47             index  index.html index.htm;
 48         }

root@localhost ~]# systemctl restart nginx.service 

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

//命令行访问 -u 指定用户名和密码
[root@localhost html]# curl -u admin:admin http://192.168.8.137
<!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@localhost html]# 

6.12 https配置

生成证书

[root@localhost nginx]# mkdir -p /etc/pki/CA
[root@localhost nginx]# cd /etc/pki/CA/[root@localhost CA]# mkdir private
[root@localhost nginx]# cd /etc/pki/CA
[root@localhost CA]# mkdir private
[root@localhost 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@localhost 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) []:test.runtime.com
Email Address []:1@2.com
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial

//创建证书存放位置
[root@localhost CA]# mkdir /usr/local/nginx/conf/ssl
[root@localhost CA]# cd /usr/local/nginx/conf/ssl/
[root@localhost ssl]# ls
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.......................................................................................+++++
..................................+++++
e is 65537 (0x010001)
//生成证书签署请求
[root@localhost 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]: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) []:test.runtime.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@localhost ssl]# ls
nginx.csr  nginx.key



[root@localhost ssl]# vim /usr/local/nginx/conf/nginx.conf
//修改配置文件,取消下面注释
 98     server {
 99         listen       443 ssl;
100         server_name  test.runtime.com;
101 
102         ssl_certificate      ssl/nginx.crt;   //修改这一行
103         ssl_certificate_key  ssl/nginx.key;   //修改这一行
104 
105         ssl_session_cache    shared:SSL:1m;
106         ssl_session_timeout  5m;
107 
108         ssl_ciphers  HIGH:!aNULL:!MD5;
109         ssl_prefer_server_ciphers  on;
110 
111         location / {
112             root   html;
113             index  index.html index.htm;
114         }
115     }
116 

//CA签署客户端提交上来的证书
[root@localhost 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 12:03:42 2021 GMT
            Not After : Oct 27 12:03:42 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = runtime
            commonName                = test.runtime.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                64:CC:99:81:91:DD:BA:69:77:F9:56:2A:51:57:41:7D:4F:07:40:33
            X509v3 Authority Key Identifier: 
                keyid:28:68:C2:8B:93:B9:71:8F:31:9A:C0:D7:2C:53:37:74:70:62:3D:C0

Certificate is to be certified until Oct 27 12:03:42 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@localhost ssl]# systemctl restart nginx.service 
[root@localhost ssl]# 
[root@localhost ssl]# ss -antl
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:443                             0.0.0.0:*              
LISTEN           0                128                              0.0.0.0:80                              0.0.0.0:*              
LISTEN           0                128                                 [::]:22                                 [::]:*              
[root@localhost ssl]# 

在这里插入图片描述

6.13 开启状态界面

开启status:

 47         location /status {
 48             stub_status;
 49         }

访问状态页面的方式:ip+/status
在这里插入图片描述
状态页面信息详解:

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

6.14 rewrite

语法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
[root@localhost images]# pwd
/usr/local/nginx/html/images
[root@localhost images]# ls
1.jpg
[root@localhost images]# 

输入ip和路径直接访问
在这里插入图片描述

//修改文件名
[root@localhost html]# mv images imgs

在这里插入图片描述

//匹配以/images开头里面任意东西.jpg结尾的在/imgs/下找
 47         location /images {
 48             rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
 49         }

在这里插入图片描述
此处的$1用于引用(.*.jpg)匹配到的内容,又如:

 47         location /images {
 48             rewrite ^/images/(.*\.jpg)$ http://images.baidu.com break;
 49         }

在这里插入图片描述

last用法

 47          location /images {
 48             rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
 49         }
 50 
 51         location /imgs {
 52             rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
 53         }

在这里插入图片描述

 47          location /images {
 48              rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
 49          }
 50 
 51          location /imgs {
 52              rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;
 53          }

在这里插入图片描述
如上例所示,replacement可以是某个路径,也可以是某个URL

常见的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)库,基本语法如下:

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

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

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

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

6.15 if

语法:if (condition) {...}
应用场景:

  • server段
  • location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)

  • 以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)

  • 正则表达式的模式匹配操作

    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !和!*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)

  • 测试指定路径为目录的可能性(-d,!-d)

  • 测试文件的存在性(-e,!-e)

  • 检查文件是否有执行权限(-x,!-x)
    Examples:

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

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

6.15.2 防盗链案例

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

6.16 反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。

nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。

但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。

Http Proxy模块,功能很多,最常用的是proxy_passproxy_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 {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,翻墙等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。

定义好upstream后,需要在server段内添加如下内容:

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}

7. nginx实现负载均衡

环境说明:

系统平台主机IP需要安装的服务
rhel-8.2192.168.8.129(nginx)nginx
rhel-8.2192.168.8.130(node1)httpd
rhel-8.2192.168.8.137(node2)httpd

node1主机上操作

[root@node1 ~]# yum -y install httpd
[root@node1 ~]# echo node1 > /var/www/html/index.html
[root@node1 ~]# cat /var/www/html/index.html 
node1
[root@node1 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@node1 ~]# 

在这里插入图片描述
node2主机上操作

[root@node2 ~]# yum -y install httpd
[root@node2 ~]# echo node2 > /var/www/html/index.html
[root@node2 ~]# cat /var/www/html/index.html 
node2
[root@node2 ~]# systemctl enable --now httpd

在这里插入图片描述
nginx主机上操作

//修改配置文件,添加以下内容
 [root@nginx nginx]# vim /usr/local/nginx/conf/nginx.conf

 33     #gzip  on;
 34     upstream webservers {
 35         server 192.168.8.130;
 36         server 192.168.8.137;
 37     }


 46         location / {
 47             proxy_pass http://webservers;
 48         }

[root@nginx nginx]# systemctl restart nginx.service 
[root@nginx nginx]# 

浏览器输入master主机IP访问
在这里插入图片描述
再次访问
在这里插入图片描述

8. nginx实现动静分离

环境说明:

系统平台主机IP需要安装的服务
rhel-8.2192.168.8.129(nginx)nginx
rhel-8.2192.168.8.130(node1)lnmp
rhel-8.2192.168.8.137(node2)httpd

node1主机上操作

安装nginx

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

//安装依赖环境
[root@node1 ~]# yum -y install pcre-devel pcre gcc gcc-c++ openssl-devel zlib zlib-devel make vim wget openssl openssl-devel gd-devel
//创建日志存放目录
[root@node1 ~]# mkdir -p /var/log/nginx
[root@node1 ~]# chown nginx.nginx /var/log/nginx/
//下载nginx
[root@node1 ~]# cd /usr/src/
[root@node1 src]# wget https://nginx.org/download/nginx-1.20.1.tar.gz
--2021-10-29 14:50:49--  https://nginx.org/download/nginx-1.20.1.tar.gz
正在解析主机 nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|3.125.197.172|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1061461 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.20.1.tar.gz”

nginx-1.20.1.tar.gz           100%[===============================================>]   1.01M   427KB/s  用时 2.4s    

2021-10-29 14:50:53 (427 KB/s) - 已保存 “nginx-1.20.1.tar.gz” [1061461/1061461])

[root@node1 src]# ls
debug  kernels  nginx-1.20.1.tar.gz
[root@node1 src]# 
//编译安装
[root@node1 src]# tar xf nginx-1.20.1.tar.gz 
[root@node1 src]# cd nginx-1.20.1/
[root@node1 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@node1 nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
//使用service控制nginx
[root@node1 nginx-1.20.1]# cat /usr/lib/systemd/system/nginx.service 
[Unit]
Description=Nginx server daemon
After=network.target 

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx 
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
[root@node1 nginx-1.20.1]# 
[root@node1 nginx-1.20.1]# systemctl daemon-reload 
[root@node1 nginx-1.20.1]# systemctl enable --now nginx.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@node1 nginx-1.20.1]# 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                             [::]:*            
[root@node1 nginx-1.20.1]# 

浏览器输入IP访问
在这里插入图片描述
安装mysql

//安装依赖包
[root@node1 ~]# yum -y install ncurses-devel openssl-devel openssl cmake mariadb-devel
//创建用户和组
[root@node1 ~]# useradd -r -M -s /sbin/nologin mysql
//下载mysql安装包
[root@node1 ~]# cd /usr/src/
[root@node1 src]# ls
debug  kernels  mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz  nginx-1.20.1  nginx-1.20.1.tar.gz
[root@node1 src]# tar xf mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@node1 src]# ln -s /usr/local/mysql-5.7.34-linux-glibc2.12-x86_64/ /usr/local/mysql
[root@node1 src]# 
//添加环境变量
[root@node1 src]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@node1 src]# source /etc/profile.d/mysql.sh 
[root@node1 src]# echo $PATH
/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[root@node1 src]# 
//创建数据存放目录
[root@node1 src]# mkdir -p /opt/data
[root@node1 src]# chown -R mysql.mysql /opt/data/
//初始化数据库
root@node1 src]# mysqld --initialize-insecure --user mysql --datadir /opt/data/
2021-10-29T07:06:45.754786Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2021-10-29T07:06:45.881619Z 0 [Warning] InnoDB: New log files created, LSN=45790
2021-10-29T07:06:45.903520Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2021-10-29T07:06:45.912371Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: c71f27c6-3886-11ec-87d0-000c29297f87.
2021-10-29T07:06:45.912838Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2021-10-29T07:06:46.356925Z 0 [Warning] CA certificate ca.pem is self signed.
2021-10-29T07:06:46.664219Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
[root@node1 src]# 
//生成配置文件
[root@node1 src]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
[root@node1 src]# 

//使用service控制mysql
[root@node1 src]# cat /usr/lib/systemd/system/mysql.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
[root@node1 src]# 

[root@node1 src]# vim /usr/local/mysql/support-files/mysql.server 
46 basedir=/usr/local   //修改这两行
47 datadir=/opt/data
//启动服务
[root@node1 ~]# systemctl daemon-reload 
[root@node1 ~]# systemctl enable --now mysql.service 
Created symlink /etc/systemd/system/multi-user.target.wants/mysql.service → /usr/lib/systemd/system/mysql.service.
[root@node1 ~]# 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              80                                   *:3306                              *:*            
LISTEN         0              128                               [::]:22                             [::]:*            
[root@node1 ~]# 

//设置密码
[root@node1 ~]# yum -y install ncurses-compat-libs
[root@node1 ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.34 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

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

mysql> 

安装php

//安装epel源
[root@node1 ~]# yum -y install epel-release

//安装依赖包
[root@node1 ~]# 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 libsqlite3x-devel php-mysqlnd libzip-devel

[root@node1 ~]# 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@node1 ~]# wget https://www.php.net/distributions/php-8.0.10.tar.gz
--2021-10-29 15:18:03--  https://www.php.net/distributions/php-8.0.10.tar.gz
正在解析主机 www.php.net (www.php.net)... 185.85.0.29, 2a02:cb40:200::1ad
正在连接 www.php.net (www.php.net)|185.85.0.29|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:16169042 (15M) [application/octet-stream]
正在保存至: “php-8.0.10.tar.gz”

php-8.0.10.tar.gz             100%[===============================================>]  15.42M   190KB/s  用时 35s     

2021-10-29 15:18:42 (445 KB/s) - 已保存 “php-8.0.10.tar.gz” [16169042/16169042])

[root@node1 ~]#  tar xf php-8.0.10.tar.gz -C /usr/local/
//编译安装
[root@node1 ~]# cd /usr/local/
[root@node1 local]# ls
bin  games    lib    libexec  mysql-5.7.34-linux-glibc2.12-x86_64  php-8.0.10  share
etc  include  lib64  mysql    nginx                                sbin        src
[root@node1 local]# cd php-8.0.10/
[root@node1 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@node1 php-8.0.10]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
//安装后配置
[root@node1 php-8.0.10]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh
[root@node1 php-8.0.10]# source /etc/profile.d/php.sh 
[root@node1 php-8.0.10]# which php
/usr/local/php8/bin/php
[root@node1 php-8.0.10]# 

//配置php-fpm
[root@node1 php-8.0.10]# cp php.ini-production /etc/php.ini
cp:是否覆盖'/etc/php.ini'? y
[root@node1 php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@node1 php-8.0.10]# chmod +x /etc/rc.d/init.d/php-fpm
[root@node1 php-8.0.10]# cp /usr/local/php8/etc/php-fpm.conf.default /usr/local/php8/etc/php-fpm.conf
[root@node1 php-8.0.10]# cp /usr/local/php8/etc/php-fpm.d/www.conf.default /usr/local/php8/etc/php-fpm.d/www.conf
[root@node1 php-8.0.10]# service php-fpm start
Starting php-fpm  done
[root@node1 php-8.0.10]# ss -antl
State          Recv-Q         Send-Q                   Local Address:Port                   Peer Address:Port         
LISTEN         0              128                          127.0.0.1:9000                        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              80                                   *:3306                              *:*            
LISTEN         0              128                               [::]:22                             [::]:*            
[root@node1 php-8.0.10]# 

//使用service控制nginx
[root@node1 php-8.0.10]# vim /usr/lib/systemd/system/php-fpm.service
[root@node1 php-8.0.10]# service php-fpm stop
Gracefully shutting down php-fpm . done
[root@node1 php-8.0.10]# cat /usr/lib/systemd/system/php-fpm.service 
[Unit]
Description=php server daemon
After=network.target

[Service]
Type=forking
ExecStart=/etc/init.d/php-fpm start
ExecStop=/etc/init.d/php-fpm stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target

[root@node1 php-8.0.10]# systemctl daemon-reload 
[root@node1 php-8.0.10]# systemctl enable --now php-fpm.service 
Synchronizing state of php-fpm.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.
Executing: /usr/lib/systemd/systemd-sysv-install enable php-fpm
Created symlink /etc/systemd/system/multi-user.target.wants/php-fpm.service → /usr/lib/systemd/system/php-fpm.service.
[root@node1 php-8.0.10]# 
//创建php访问界面
[root@node1 ~]# vim /usr/local/nginx/html/index.php
[root@node1 ~]# cat /usr/local/nginx/html/index.php
<?php
        phpinfo();
?>
[root@node1 ~]# 
修改nginx配置文件
[root@node1 ~]# vim /usr/local/nginx/conf/nginx.conf

 43         location / {
 44             root   html;
 45             index  index.php index.html index.htm;   //修改这一行
 46         }

 65         location ~ \.php$ {
 66             root           html;
 67             fastcgi_pass   127.0.0.1:9000;
 68             fastcgi_index  index.php;
 69             fastcgi_param  SCRIPT_FILENAME  $Document_Root$fastcgi_script_name;   //修改这一行
 70             include        fastcgi_params;
 71         }
[root@node1 ~]# systemctl restart nginx.service 

浏览器输入IP访问
在这里插入图片描述
node2主机上操作

[root@node2 ~]# yum -y install httpd
[root@node2 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@node2 ~]# 

浏览器输入IP访问
在这里插入图片描述
nginx主机上操作

[root@nginx nginx]# cat /usr/local/nginx/conf/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;


events {
    worker_connections  1024;
}


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;

    upstream static {                    
        server 192.168.8.137;   //设置静态访问
    }

    upstream dynamic {          //设置动态访问             
        server 192.168.8.130;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://static;      //访问,静态处理
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        location ~ \.php$ {
            proxy_pass   http://dynamic;     //访问.php结尾的动态处理
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

}
[root@nginx nginx]# 
[root@nginx nginx]# systemctl restart nginx.service 

在浏览器输入master主机IP访问的是静态资源在这里插入图片描述

在浏览器输入master主机IP+/index.php访问的是动态资源

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彭宇栋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值