模块与工作原理

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

模块分类

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

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

用户根据自己的需要开发的模块都属于第三方模块。
nginx模块从功能上分为三类,分别是:

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

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

nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:

  • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部
  • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
  • 配置模块:提供包含机制

更多的指令,请参考nginx官方文档

nginx的工作原理

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

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

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

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request。

worker 进程中,ngx_worker_process_cycle()函数就是这个无限循环的处理函数。在这个函数中,一个请求的简单处理流程如下:

  1. 操作系统提供的机制(例如 epoll, kqueue 等)产生相关的事件。
  2. 接收和处理这些事件,如是接收到数据,则产生更高层的 request 对象。
  3. 处理 request 的 header 和 body。
  4. 产生响应,并发送回客户端。
  5. 完成 request 的处理。
  6. 重新初始化定时器及其他事件。

    多进程模型的处理方式:
  • 首先,master进程一开始就会根据我们的配置,来建立需要listen的网络socket fd,然后fork出多个worker进程。
  • 其次,根据进程的特性,新建立的worker进程,也会和master进程一样,具有相同的设置。因此,其也会去监听相同ip端口的套接字socket fd。
    然后,这个时候有多个worker进程都在监听同样设置的socket fd,意味着当有一个请求进来的时候,所有的worker都会感知到。这样就会产生所谓的“惊群现象”。为了保证只会有一个进程成功注册到listenfd的读事件,nginx中实现了一个“accept_mutex”类似互斥锁,只有获取到这个锁的进程,才可以去注册读事件。其他进程全部accept 失败。
  • 最后,监听成功的worker进程,读取请求,解析处理,响应数据返回给客户端,断开连接,结束。因此,一个request请求,只需要worker进程就可以完成。

nginx模块一次常规的HTTP请求和响应的过程

一个典型的HTTP处理周期:
7. 客户端发送HTTP请求
8. Nginx基于配置文件中的位置选择一个合适的处理模块
9. (如果有)负载均衡模块选择一台后端服务器
10. 处理模块进行处理并把输出缓冲放到第一个过滤模块上
11. 第一个过滤模块处理后输出给第二个过滤模块
12. 然后第二个过滤模块又到第三个
13. 依此类推 –> 最后把响应发给客户端。

Nginx本身做的工作实际很少,当它接到一个HTTP请求时,它仅仅是通过查找配置文件将此次请求映射到一个location block,而此location中所配置的各个指令则会启动不同的模块去完成工作,因此模块可以看做Nginx真正的劳动工作者。

基本的WEB服务请求步骤

  1. 建立连接 — 接受一个客户端连接,或者如果不希望与这个客户端建立连接,就将其关闭。
  2. 接收请求 — 从网络中读取一条 HTTP 请求报文。
  3. 处理请求 — 对请求报文进行解释,并采取行动。
  4. 访问资源 — 访问报文中指定的资源。
  5. 构建响应 — 创建带有正确首部的 HTTP 响应报文。
  6. 发送响应 — 将响应回送给客户端。
  7. 记录事务处理过程 — 将与已完成事务有关的内容记录在一个日志文件中。

nginx部署

nginx的安装

# 关闭防火墙和selinux
[root@localhost ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# reboot
[root@localhost ~]# getenforce 0
Disabled
# 创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
# 安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ vim wget make
[root@localhost ~]# yum -y groups mark install 'Development Tools'
# 创建日志存放目录
[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 http://nginx.org/download/nginx-1.12.0.tar.gz
# 编译安装
[root@localhost src]# ls
debug  kernels  nginx-1.12.0.tar.gz
[root@localhost src]# tar xf nginx-1.12.0.tar.gz
[root@localhost src]# cd nginx-1.12.0
[root@localhost nginx-1.12.0]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@localhost nginx-1.12.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
# 配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# . /etc/profile.d/nginx.sh# 启动nginx
[root@localhost ~]# nginx
[root@localhost ~]# ss -anlt
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*
LISTEN   0        128                 [::]:22               [::]:*
# 写service文件让nginx开机自启
[root@localhost ~]# cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx
After=network.target[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true[Install]
WantedBy=multi-user.target
EOF
[root@localhost ~]# systemctl daemon-reload
[root@localhost ~]# systemctl enable --now  nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xe" for details.

nginx的配置文件详解

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

  • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
  • 可以在启动nginx时通过-c选项来指定要读取的配置文件
    nginx常见的配置文件及其作用
配置文件 作用
nginx.conf nginx的基本配置文件
mime.types MIME类型关联的扩展文件
fastcgi.conf 与fastcgi相关的配置
proxy.conf 与proxy相关的配置
sites.conf 配置nginx提供的网站,包括虚拟主机

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

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

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value
    用于调试、定位问题的配置参数
    是否以守护进程方式运行Nginx
    守护进程(daemon)是脱离终端并且在后台运行的进程。它脱离终端是为了避免进程执行过程中的信息在任何终端上显示,这样一来,进程也不会被任何终端所产生的信息所打断。Nginx毫无疑问是一个需要以守护进程方式运行的服务,因此,默认都是以这种方式运行的。
daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  1;
daemon off;[root@localhost ~]# nginx -s stop;nginx

正常运行必备的配置参数

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

# user USERNAME [GROUPNAME]      //指定允许worker进程的用户和组
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx nginx;# pid /path/to/pid_file           //指定nginx守护进程的pid文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
pid        logs/nginx.pid;
[root@localhost ~]# ls /usr/local/nginx/logs/
nginx.pid
[root@localhost ~]# systemctl stop nginx.service
[root@localhost ~]# ls /usr/local/nginx/logs/# worker_rlimit_nofile number //设置所有woker进程最大可以打开的文件数,默认1024# worker_rlimit_core size      //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

优化性能的配置参数

worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:0000 0001   //第一颗cpu核心0000 0010   //第二颗cpu核心0000 0100   //第三颗cpu核心0000 1000   //第四颗cpu核心0001 0000   //第五颗cpu核心0010 0000   //第六颗cpu核心0100 0000   //第七颗cpu核心1000 0000   //第八颗cpu核心#查看cpu
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes  3;
worker_cpu_affinity 0001 0010 0100;
[root@localhost ~]# systemctl restart nginx.service
[root@localhost ~]# ps -ef | grep nginx
root        1571       1  0 23:13 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1572    1571  0 23:13 ?        00:00:00 nginx: worker process
nginx       1573    1571  0 23:13 ?        00:00:00 nginx: worker process
nginx       1574    1571  0 23:13 ?        00:00:00 nginx: worker process
root        1576    1485  0 23:13 pts/0    00:00:00 grep --color=auto nginx[root@localhost ~]# top
top - 23:31:29 up 22 min,  1 user,  load average: 0.00, 0.00, 0.00
Tasks: 223 total,   1 running, 222 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   3752.0 total,   3300.8 free,    216.8 used,    234.4 buff/cache
MiB Swap:   4044.0 total,   4044.0 free,      0.0 used.   3305.5 avail Mem PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                       1 root      20   0  242256  10628   8180 S   0.0   0.3   0:00.92 systemd                                                       2 root      20   0       0      0      0 S   0.0   0.0   0:00.00 kthreadd                                                      3 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 rcu_gp    #按shift+f ,输入nginx,回车Locate string nginxPID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                       1485 root      20   0   26516   4928   3452 S   0.0   0.1   0:00.03 bash                                                          1571 root      20   0   80256   1092     56 S   0.0   0.0   0:00.00 nginx                                                         1572 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                         1573 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                         1574 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx   # 按f, 将光标移到  P       = Last Used Cpu (SMP)
Fields Management for window 1:Def, whose current sort field is %CPUNavigate with Up/Dn, Right selects for move then <Enter> or Left commits,'d' or <Space> toggles display, 's' sets sort.  Use 'q' or <Esc> to end!* PID     = Process Id             WCHAN   = Sleeping in Function
* USER    = Effective User Name    Flags   = Task Flags <sched.h>
* PR      = Priority               CGROUPS = Control Groups
* NI      = Nice Value             SUPGIDS = Supp Groups IDs
* VIRT    = Virtual Image (KiB)    SUPGRPS = Supp Groups Names
* RES     = Resident Size (KiB)    TGID    = Thread Group Id
* SHR     = Shared Memory (KiB)    OOMa    = OOMEM Adjustment
* S       = Process Status         OOMs    = OOMEM Score current
* %CPU    = CPU Usage              ENVIRON = Environment vars
* %MEM    = Memory Usage (RES)     vMj     = Major Faults delta
* TIME+   = CPU Time, hundredths   vMn     = Minor Faults delta
* COMMAND = Command Name/Line      USED    = Res+Swap Size (KiB) PPID    = Parent Process pid     nsIPC   = IPC namespace Inode UID     = Effective User Id      nsMNT   = MNT namespace Inode RUID    = Real User Id           nsNET   = NET namespace Inode RUSER   = Real User Name         nsPID   = PID namespace Inode SUID    = Saved User Id          nsUSER  = USER namespace InodeSUSER   = Saved User Name        nsUTS   = UTS namespace Inode GID     = Group Id               LXC     = LXC container name  GROUP   = Group Name             RSan    = RES Anonymous (KiB) PGRP    = Process Group Id       RSfd    = RES File-based (KiB)TTY     = Controlling Tty        RSlk    = RES Locked (KiB)    TPGID   = Tty Process Grp Id     RSsh    = RES Shared (KiB)    SID     = Session Id             CGNAME  = Control Group name  nTH     = Number of Threads      NU      = Last Used NUMA node P       = Last Used Cpu (SMP) TIME    = CPU Time            SWAP    = Swapped Size (KiB)  CODE    = Code Size (KiB)     DATA    = Data+Stack (KiB)    nMaj    = Major Page Faults   nMin    = Minor Page Faults   nDRT    = Dirty Pages Count # 空格选择,按qPID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                      P1571 root      20   0   80256   1092     56 S   0.0   0.0   0:00.00 nginx                                                        21572 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                        01573 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                        11574 nginx     20   0  111708   6276   4700 S   0.0   0.2   0:00.00 nginx                                                        2timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值 number取19~-20,数值越低优先级越高
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
worker_priority -20;
[root@localhost ~]# systemctl restart nginx.service
[root@localhost ~]# ps -elf |grep nginx
1 S root        1750       1  0  80   0 - 20064 -      00:21 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
5 S nginx       1751    1750  0  60 -20 - 27927 do_epo 00:21 ?        00:00:00 nginx: worker process
5 S nginx       1752    1750  0  60 -20 - 27927 do_epo 00:21 ?        00:00:00 nginx: worker process
5 S nginx       1753    1750  0  60 -20 - 27927 do_epo 00:21 ?        00:00:00 nginx: worker process
0 S root        1756    1485  0  80   0 -  3086 -      00:22 pts/0    00:00:00 grep --color=auto nginx

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

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
events {worker_connections  10240;
}[root@localhost ~]# dnf -y install httpd-tools
[root@localhost ~]# ab  -n 3000 http://192.168.8.132/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.8.132 (be patient)
Completed 300 requests
Completed 600 requests
Completed 900 requests
Completed 1200 requests
Completed 1500 requests
Completed 1800 requests
Completed 2100 requests
Completed 2400 requests
Completed 2700 requests
Completed 3000 requests
Finished 3000 requestsServer Software:        nginx/1.20.1
Server Hostname:        192.168.111.141
Server Port:            80Document Path:          /index.html
Document Length:        612 bytesConcurrency Level:      1
Time taken for tests:   0.376 seconds
Complete requests:      3000
Failed requests:        0
Total transferred:      2535000 bytes
HTML transferred:       1836000 bytes
Requests per second:    7974.21 [#/sec] (mean)
Time per request:       0.125 [ms] (mean)
Time per request:       0.125 [ms] (mean, across all concurrent requests)
Transfer rate:          6580.28 [Kbytes/sec] receivedConnection Times (ms)min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       0
Processing:     0    0   0.0      0       1
Waiting:        0    0   0.0      0       1
Total:          0    0   0.0      0       1Percentage of the requests served within a certain time (ms)50%      066%      075%      080%      090%      095%      098%      099%      0100%      1 (longest request)

网络连接相关的配置参数

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;    //发送响应报文的超时时长

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;      //.php文件路径include fastcgi_params;
}

nginx.conf配置文件案例
更改默认端口号以及进程数和指定特定配置文件

[root@localhost conf]# head nginx.conf#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;// 使用80端口server {listen       80;server_name  localhost;// 使用源文件运行进程数如下
[root@localhost conf]# ps -ef | grep nginx
root      257815       1  0 16:46 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx     257816  257815  0 16:46 ?        00:00:00 nginx: worker process
root      258199  102060  0 16:46 pts/0    00:00:00 grep --color=auto nginx// 将源文件以及mime.types文件copy一份到/opt目录中
[root@localhost conf]# cp nginx.conf /opt/
[root@localhost conf]# cp mime.types /opt/
[root@localhost conf]# cd /opt/
[root@localhost opt]# ls
mime.types  nginx.conf
[root@localhost opt]# nginx -t -c /opt/nginx.conf
nginx: the configuration file /opt/nginx.conf syntax is ok
nginx: configuration file /opt/nginx.conf test is successful// 修改 worker_rlimit_nofile number; 参数为4
#user  nobody;
worker_processes  4;server {listen       8070;server_name  localhost;使用nginx服务控制命令重启并指定配置文件路径
[root@localhost opt]# nginx -s stop;nginx -c /opt/nginx.conf
[root@localhost ~]# ss -antl
State  Recv-Q Send-Q Local Address:Port   Peer Address:Port Process
LISTEN 0      128          0.0.0.0:22          0.0.0.0:*
LISTEN 0      128          0.0.0.0:8070        0.0.0.0:*
LISTEN 0      128             [::]:22             [::]:*  [root@localhost ~]# ps -ef | grep nginx
root      276931       1  0 16:56 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx     276932  276931  0 16:56 ?        00:00:00 nginx: worker process
nginx     276933  276931  0 16:56 ?        00:00:00 nginx: worker process
nginx     276934  276931  0 16:56 ?        00:00:00 nginx: worker process
nginx     276935  276931  0 16:56 ?        00:00:00 nginx: worker process
root      283466  276242  0 16:58 pts/2    00:00:00 grep --color=auto nginx

报错

解决方法

[root@localhost nginx-1.12.0]# vim objs/Makefile
CFLAGS =  -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werrori -g
// 找到 -Werrori 后将其去掉

[root@localhost nginx-1.12.0]# vim src/os/unix/ngx_user.c
#ifdef __GLIBC__/* work around the glibc bug */cd.current_salt[0] = ~salt[0];
#endif
// 把cd.current_salt[0] = ~salt[0];前后加上/* cd.current_salt[0] = ~salt[0];*/

错误页面配置

[root@localhost conf]# vim nginx.conf
error_page  404              /404.html;
// 把这一行的注释取消
[root@localhost html]# vim 404.html<html>
<head>
<title>test</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost html]# systemctl restart nginx

平滑升级加echo功能获取现有的程序编译的参数 -V

  1. 获取新版本的软件包或功能包
  2. 将新功能或新版本进行编译
  3. 备份原程序
  4. 替换原程序
#功能包下载
https://github.com/openresty/echo-nginx-module.git[root@localhost src]# unzip echo-nginx-module-master.zip
[root@localhost src]# ls
debug  echo-nginx-module-master  kernels  nginx-1.20.1  nginx-1.20.1.tar.gz echo-nginx-module-master.zip#解压nginx
[root@localhost src]# ls
debug  kernels  nginx-1.20.1  nginx-1.20.1.tar.gz
[root@localhost src]# rm -rf nginx-1.20.1
[root@localhost src]# tar xf nginx-1.20.1.tar.gz [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=../echo-nginx-module-master[root@localhost nginx-1.20.1]# make[root@localhost 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#备份nginx
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /opt/[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        5652       1  0 22:24 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx       5653    5652  0 22:24 ?        00:00:00 nginx: worker process
nginx       5654    5652  0 22:24 ?        00:00:00 nginx: worker process
nginx       5655    5652  0 22:24 ?        00:00:00 nginx: worker process
root        5657    1623  0 22:24 pts/1    00:00:00 grep --color=auto nginx[root@localhost conf]# vim nginx.conflocation /test {echo "test";}
[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 src]# cp nginx-1.20.1/objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y

localtion配置

通过指定模式来与客户端请求的URI相匹配
功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
语法:location [ 修饰符 ] pattern {…}
常用修饰符:

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

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

location = /testa {echo "test2";}
[root@localhost ~]# curl 192.168.111.141/testa
test2
[root@localhost ~]# curl 192.168.111.141/testa?abc
test2

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

abclocation ~ ^/abc$ {echo "abc";}
[root@localhost ~]# curl 192.168.111.141/abc
abc
[root@localhost ~]# curl 192.168.111.141/abc?abc
abc

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

       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

查找顺序和优先级:

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

访问配置

用于location段

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

#拒绝本机访问
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {deny   192.168.111.1;root   html;index  index.html index.htm;}

#允许本机访问,其他全部拒绝
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {allow   192.168.111.1;deny all;root   html;index  index.html index.htm;}
[root@localhost ~]# curl 192.168.111.141
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

用户认证

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

user_auth_file内容格式为:

username:password

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

[root@localhost ~]# yum -y install httpd-tools
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass admin
New password:
Re-type new password:
Adding password for user admin[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {auth_basic "Welcome";auth_basic_user_file "conf/.pass";root   html;index  index.html index.htm;}


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

https配置

生成证书

#生成一对密钥
[root@localhost ~]# mkdir -p /etc/pki/CA
[root@localhost ~]# 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.neawalke.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 ~]# cd /usr/local/nginx/conf/ssl/
[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.neawalke.com
Email Address []:1@2.comPlease enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:#修改nginx配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.confserver {listen       443 ssl;server_name  test.neawalke.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;}}#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)ValidityNot Before: Oct 27 15:46:45 2021 GMTNot After : Oct 27 15:46:45 2022 GMTSubject:countryName               = CNstateOrProvinceName       = HBorganizationName          = runtimeorganizationalUnitName    = runtimecommonName                = test.neawalke.comemailAddress              = 1@2.comX509v3 extensions:X509v3 Basic Constraints: CA:FALSENetscape Comment: OpenSSL Generated CertificateX509v3 Subject Key Identifier: DB:C0:67:A9:96:4F:D8:67:60:8D:C0:6E:E7:B9:96:A9:70:7A:0E:62X509v3 Authority Key Identifier: keyid:E6:F5:AE:F8:57:F4:37:2F:EE:29:36:75:E9:CB:0E:45:FE:80:8A:72Certificate is to be certified until Oct 27 15:46:45 2022 GMT (365 days)
Sign the certificate? [y/n]:y1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated#当需两台服务器实现https,需做如下操作
//客户端把证书签署请求文件发送给CA
scp httpd.csr root@CA端IP:/root//CA把签署好的证书httpd.crt发给客户端
scp httpd.crt root@客户端IP:/etc/httpd/ssl/

开启状态界面

# 开启status
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /status {stub_status;}


状态页面:

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

状态页面监控
环境:

主机 IP 服务
zabbix 192.168.111.141 zabbix_server
server 192.168.111.142 zabbix_agent、nginx
#监控脚本
[root@localhost scripts]# cat nginx_status.sh
#!/bin/bashstatus=$(curl -s 192.168.111.142/status |awk 'NR==4{print $6}')
if [ $status -eq 0 ];thenecho "0"
elseecho "1"
fi[root@localhost etc]# vim zabbix_agentd.conf
UnsafeUserParameters=1 #默认为0。修改为1,打开自定义监控功能
······
UserParameter=check_status,/scripts/nginx_status.sh



rewrite

URL重定向
#语法:rewrite regex replacement flag;rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

[root@localhost html]# mv images  img
[root@localhost html]# ls
404.html  50x.html  img  index.html

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /images {rewrite ^/images/(.*\.jpg)$ /img/$1 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

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

#使用last,当前匹配结束时,继续下一个匹配
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /images {rewrite ^/images/(.*\.jpg)$ /img/$1 last;}location /img {rewrite ^/img/(.*)$ https://www.baidu.com/ last;}

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

nginx实现动静分离

环境说明:

系统平台 主机IP 需要安装的服务
rhel-8.2 192.168.111.142(nginx) nginx
rhel-8.2 192.168.111.141(node1) lnmp
rhel-8.2 192.168.111.145(node2) httpd

node1主机
安装nginx

//创建系统用户nginx
[root@node1 ~]# useradd -r -M -s /sbin/nologin nginx
//创建日志存放目录
[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]# 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                             [::]:*


安装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]# 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]# 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]# 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]# 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 ~]# 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> quit

安装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
//配置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                             [::]:*
//使用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.
//创建php访问界面
[root@node1 ~]# vim /usr/local/nginx/html/index.php
[root@node1 ~]# cat /usr/local/nginx/html/index.php
<?phpphpinfo();
?>
修改nginx配置文件
[root@node1 ~]# vim /usr/local/nginx/conf/nginx.conf43         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



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.


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.111.145;   //设置静态访问}upstream dynamic {          //设置动态访问             server 192.168.111.141;}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]# systemctl restart nginx.service

在浏览器输入nginx主机IP访问的是静态资源

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

nginx工作原理及配置相关推荐

  1. Nginx工作原理及相关介绍

    Nginx工作原理及相关介绍 一.Nginx工作原理与模块介绍 1.Nginx基本工作原理 NGINX以高性能的负载均衡器,缓存,和web服务器闻名.Nginx由内核和模块组成,其中,内核的设计非常微 ...

  2. Nginx系列1: 正向代理和反向代理、Nginx工作原理、Nginx常用命令和升级、搭建Nginx负载均衡

    一.什么是正向代理.什么是反向代理 1. 正向代理,意思是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器 ...

  3. nginx工作原理和实现高并发请求的原因

    一.进程.线程? 进程是具有一定独立功能的,在计算机中已经运行的程序的实体.在早期系统中(如linux 2.4以前),进程是基本运作单位,在支持线程的系统中(如windows,linux2.6)中,线 ...

  4. MPLS之LDP的工作原理和配置

    LDP的工作原理和配置 LDP的基本概念和工作机制 MPLS标签分发模式 LDP的基础配置 一.LDP的基本概念和工作机制 首先MPLS是一种根据标签报文中携带的标签来转发数据的技术. MPLS的一个 ...

  5. 36.DAC工作原理与配置

    DAC工作原理与配置 参考资料 STM32FX开发板 <STM32FX开发指南-HAL库版本>-第X章 DAC实验 STM32FXxx官方资料: <STM32FX中文参考手册> ...

  6. 第五章 路由器的工作原理及其配置

    第五章 路由器的工作原理及其配置 5.1 广域网服务 WAN连接的目的是在两个远离的网络之间尽可能高效率传递数据.连接的效率越高,到最终用户的连接就越透明.WAN连接通常比L A N连接要慢.例如,一 ...

  7. NGINX工作原理解析

    1 反向代理 1.1 概念 反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给intern ...

  8. JAVA开发运维(nginx工作原理)

    nginx源码目录结构: . ├── auto 自动检测系统环境以及编译相关的脚本 │ ├── cc 关于编译器相关的编译选项的检测脚本 │ ├── lib nginx编译所需要的一些库的检测脚本 │ ...

  9. Nginx工作原理和优化、漏洞。

    http://blog.csdn.net/hguisu/article/details/8930668 (排名100多bolg写的很好) 1.  Nginx的模块与工作原理 Nginx由内核和模块组成 ...

  10. Nginx工作原理和优化、漏洞(转)

    查看安装了哪些模块命令: [root@RG-PowerCache-X xcache]# nginx/sbin/nginx -V nginx version: nginx/1.2.3 built by  ...

最新文章

  1. 【Interfacenavigation】通知概述(36)
  2. Android 聊天软件客户端
  3. CF1043E Train Hard, Win Easy
  4. maven打包忽略注解_maven打包后pom.properties中的注释问题-阿里云开发者社区
  5. 华为服务器虚拟化概念,华为服务器虚拟化助力IT信息化建设
  6. 微型计算机如何开声音,MP3声控录音机
  7. Scrapy 框架爬取豆瓣电影的信息(包括图片)和电影评论-2
  8. 开源项目推荐:SCADA组态软件Qt,kanzi,C#,MFC和WEB大全(收藏版)
  9. c盘减肥//请在阅读本文之前查看你C盘的可用空间
  10. 计算机驱动空间的c盘不足怎么办,如果C驱动器空间不足,该怎么办
  11. 社会性动物(艾略特•阿伦森)
  12. 大觉山漂流,男人的欢笑女人的尖叫
  13. 使用U盘制作系统盘(龙芯镜像)
  14. 通过计算机名查找当前域用户名,局域网中怎样通过IP查找计算机名
  15. 删除 linux的ln文件夹,详解Linux ln 命令
  16. java工具包Lombok
  17. Spring Boot 的配置文件有哪几种格式?它们有什么区别?
  18. fiddler下载及安装
  19. uni-app使用map组件开发map地图,获取后台返回经纬度进行标点
  20. 写给MatheMagician读者的新年来信2

热门文章

  1. java完全自学手册txt下载
  2. 细说php完美分页类
  3. 2009福州数学建模题目及答案
  4. c语言jj斗地主源码,GitHub - choushane/cocoscreator-ddz: cocos-斗地主,客户端和服务端(node.js socket.io)...
  5. Linux使文件变成二进制,linux 二进制文件显示方法
  6. html打印word文档,HTML文件到WORD文档双面打印三步曲
  7. 计算机底层逻辑无法仿造大脑,重塑世界的底层逻辑|读《终极算法》
  8. 将Chrome浏览器默认保存离线网页为“多个文件”设置为“单个文件”即单个mhtml文件
  9. Vue3 JSON编辑器
  10. 依据余弦相似度查找常用汉字形似字