nginx

nginx

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网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

nginx的特性与优点

nginx的特性

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

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

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

nginx的功能及应用类别

nginx的基本功能

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

nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制

nginx的应用类别

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

nginx的模块分类

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

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工作原理

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

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

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

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request
在这里插入图片描述
在这里插入图片描述
web服务请求资源
在这里插入图片描述
一次完整的web访问流程简析:

  • client:输入网址–>发起http request–>等待web server响应.

  • server:收到client请求–>加载资源–>构建响应报文,发给client.

client发起http请求:

  1. client将键入的域名解析为server端的IP地址(DNS解析).
  2. client与server进行TCP连接(三次握手).
  3. client与web server数据传输.
  4. client与web server断开TCP连接(四次挥手).
  5. client解释HTML文档,浏览器渲染,将在屏幕上显示渲染后的图形结果。

server收到client请求时:

  1. http request请求首先到达server端的公网ip上(公网ip一般配置在硬件防火墙上).
  2. 经过防火墙过滤之后,到达负载均衡层(可能涉及四层负载均衡和七层负载均衡),负载均衡将请求报文往后端Real Server调度.
  3. 经过lvs调度至后端RS上,此时后端提供web服务的一般是Nginx(Apache也可能),Nginx判断请求报文是动态资源还是静态资源(动静分离).
  4. 静态资源:由Nginx发起系统调用,请求内核从磁盘加载相应的资源文件,可能涉及存储服务器(资源的保存的服务器).
    动态资源:由Nginx代理给能处理动态资源的服务器(Tomcat、PHP等),还可能涉及访问数据库服务器.
  5. web server将请求的资源加载完成之后,构建响应报文发送给client.

nginx的安装

手动部署nginx

nginx官网

// 创建用户
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
[root@localhost ~]# id nginx
uid=994(nginx) gid=991(nginx)=991(nginx)

// 安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
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.21.3.tar.gz
--2021-10-25 14:55:21--  http://nginx.org/download/nginx-1.21.3.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|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1066609 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.21.3.tar.gz”

nginx-1.21.3.tar. 100%[=============>]   1.02M   291KB/s  用时 3.6s    

2021-10-25 14:55:26 (291 KB/s) - 已保存 “nginx-1.21.3.tar.gz” [1066609/1066609])


// 编译安装
[root@localhost src]# tar xf nginx-1.21.3.tar.gz 
[root@localhost src]# cd nginx-1.21.3
[root@localhost nginx-1.21.3]# ./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.21.3]# 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命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}


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

// 关闭防火墙和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

// 写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.

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

脚本部署nginx

[root@localhost nginx]# tree
.
├── nginx.sh
└── soft
    └── nginx-1.21.3.tar.gz

1 directory, 2 files

[root@localhost nginx]# vim nginx.sh 
#!/bin/bash

log_dir=/var/log
install_dir=/usr/src
config_dir=/usr/local


useradd -r -M -s /sbin/nologin nginx

#安装依赖包
yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
yum -y groups mark install 'Development Tools'


#创建日志存放目录
if [ ! -d $log_dir/nginx ];then
    mkdir -p $log_dir/nginx
    chown -R nginx.nginx $log_dir/nginx
fi

tar xf soft/nginx-1.21.3.tar.gz -C $install_dir

#install
if [ ! -d $config_dir/nginx ];then
    cd $install_dir/nginx-1.21.3
    ./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  && make && make install
fi

echo "export PATH=$config_dir/nginx/sbin:\$PATH" > /etc/profile.d/nginx.sh


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

systemctl daemon-reload
systemctl enable --now  nginx

nginx的配置文件详解

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

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

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

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

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

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

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value
[root@localhost ~]# vim /usr/local/nginx/conf
# 全局块
 user www-data;  ##用户
 worker_processes  2;  ## 默认1,一般建议设成CPU核数1-2倍
 error_log  logs/error.log; ## 错误日志路径
 pid  logs/nginx.pid; ## 进程id
 # Events块
 events {
   # 使用epoll的I/O 模型处理轮询事件。
   # 可以不设置,nginx会根据操作系统选择合适的模型
   use epoll;
   # 工作进程的最大连接数量, 默认1024个
   worker_connections  2048;
   # http层面的keep-alive超时时间
   keepalive_timeout 60;
   # 客户端请求头部的缓冲区大小
   client_header_buffer_size 2k;
 }
 # http块
 http { 
   include mime.types;  # 导入文件扩展名与文件类型映射表
   default_type application/octet-stream;  # 默认文件类型
   # 日志格式及access日志路径
   log_format   main '$remote_addr - $remote_user [$time_local]  $status '
     '"$request" $body_bytes_sent "$http_referer" '
     '"$http_user_agent" "$http_x_forwarded_for"';
   access_log   logs/access.log  main; 
   # 允许sendfile方式传输文件,默认为off。
   sendfile     on;
   tcp_nopush   on; # sendfile开启时才开启。
 
   # http server块
   # 简单反向代理
   server {
     listen       80;
     server_name  domain2.com www.domain2.com;
     access_log   logs/domain2.access.log  main;
     # 转发动态请求到web应用服务器
     location / {
       proxy_pass      http://127.0.0.1:8000;
       deny 192.24.40.8;  # 拒绝的ip
       allow 192.24.40.6; # 允许的ip   
     }
     # 错误页面
     error_page   500 502 503 504  /50x.html;
         location = /50x.html {
             root   html;
         }
   }
   # 负载均衡
   upstream backend_server {
     server 192.168.0.1:8000 weight=5; # weight越高,权重越大
     server 192.168.0.2:8000 weight=1;
     server 192.168.0.3:8000;
     server 192.168.0.4:8001 backup; # 热备
   }
   server {
     listen          80;
     server_name     big.server.com;
     access_log      logs/big.server.access.log main;
     charset utf-8;
     client_max_body_size 10M; # 限制用户上传文件大小,默认1M
     location / {
       # 使用proxy_pass转发请求到通过upstream定义的一组应用服务器
       proxy_pass      http://backend_server;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP  $remote_addr;
     } 
   }
 }

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

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

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

位置级别
file stderr syslog:server=address[,parameter=value] memory:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg

正常运行必备的配置参数
user USERNAME [GROUPNAME]; 指定运行worker进程的用户和组

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

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

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

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

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

pid        logs/nginx.pid;

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

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

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

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

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

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

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

[root@localhost ~]# nginx -s reload    //发送服务控制信号,重新加载配置文件
[root@localhost ~]# ps -ef | grep nginx
root        4980       1  0 19:22 ?        00:00:00 nginx: master process nginx
nginx       5202    4980  0 19:22 ?        00:00:00 nginx: worker process
nginx       5203    4980  0 19:22 ?        00:00:00 nginx: worker process
nginx       5204    4980  0 19:22 ?        00:00:00 nginx: worker process
nginx       5205    4980  0 19:22 ?        00:00:00 nginx: worker process
root        5564    3373  0 19:22 pts/0    00:00:00 grep --color=auto nginx
注: worker_processes的数量*worker_connections的数量=nginx所能支持的最大并发连接数量,在实际情况最大并发数建议不超过30000

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

用法
Syntax:	worker_cpu_affinity cpumask ...;
        worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main
cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心

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


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

[root@localhost ~]# ps -ef | grep nginx
root        4980       1  0 19:22 ?        00:00:00 nginx: master process nginx
nginx      29238    4980  0 19:36 ?        00:00:00 nginx: worker process
nginx      29239    4980  0 19:36 ?        00:00:00 nginx: worker process
nginx      29240    4980  0 19:36 ?        00:00:00 nginx: worker process
root       29290    3373  0 19:36 pts/0    00:00:00 grep --color=auto nginx

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

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

worker_priority number; 指明worker进程的nice值

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

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

[root@localhost ~]# nginx  -s reload
[root@localhost ~]# ps -elf | grep nginx
1 S root        4980       1  0  80   0 - 20116 -      19:22 ?        00:00:00 nginx: master process nginx
5 S nginx      50563    4980  0  60 -20 - 27944 do_epo 19:47 ?        00:00:00 nginx: worker process
5 S nginx      50564    4980  0  60 -20 - 27944 do_epo 19:47 ?        00:00:00 nginx: worker process
5 S nginx      50565    4980  0  60 -20 - 27944 do_epo 19:47 ?        00:00:00 nginx: worker process
0 S root       50900    3373  0  80   0 -  3086 -      19:47 pts/0    00:00:00 grep --color=auto nginx

事件相关的配置:event{}段中的配置参数
accept_mutex {off|on}; master 调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求

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

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

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

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

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

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

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

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

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

#pid        logs/nginx.pid;


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

网络连接相关的配置参数
keepalive_timeout number; 长连接的超时时长,默认为65s

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

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
....
http {
    include       mime.types;
    default_type  application/octet-stream;

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

    #access_log  logs/access.log  main;

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

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

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

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

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

    #access_log  logs/access.log  main;

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

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

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

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

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

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

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

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

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

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

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

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

常需要进行调整的参数

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

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

http{…}段是配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块

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

http{}段配置指令
server {}:定义一个虚拟主机

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

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

        #access_log  logs/host.access.log  main;

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

        #error_page  404              /404.html;


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


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

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

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

配置错误界面

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
error_page  404              /404.html;           #找到此行取消注释
......

// 创建自定义错误页面
[root@localhost ~]# vim  /usr/local/nginx/html/404.html    
this is a error page

// 重启服务
[root@localhost ~]# nginx -s  reload  

在这里插入图片描述

日志

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;   #访问日志


//log_format中每一段的含义
remote_addr:对应客户端的地址
remote_user:是请求客户端请求认证的用户名,如果没有开启认证模块的话是值为空。
time_local:表示nginx服务器时间
request:表示request请求头的行
status:表示response的返回状态
body_bytes_sent:表示从服务端返回给客户端的body数据大小
http_referer:表示请求的上一级页面
http_user_agent:表示agent信息
http_x_forwarded_for:会记录每一级请求中信息

//注意:此处可用变量为nginx各模块内建变量

示例

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf   #取消下列几行的注释
......
    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;
......

// 访问测试
[root@localhost ~]# curl 192.168.200.128  

[root@localhost ~]# tail -f /usr/local/nginx/logs/access.log
192.168.200.1 - - [27/Oct/2021:20:24:46 +0800] "GET /favicon.ico HTTP/1.1" 404 21 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3877.400 QQBrowser/10.8.4506.400" "-"

平滑升级

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

下载地址 github.com

// 获取现有的程序编译的参数
[root@nginx ~]# 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 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         nginx              ngx_auto_headers.h  src
autoconf.err  nginx.8            ngx_modules.c
Makefile      ngx_auto_config.h  ngx_modules.o

// 备份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      134682       1  0 20:41 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     134683  134682  0 20:41 ?        00:00:00 nginx: worker process
root      135140   87126  0 20:41 pts/2    00:00:00 grep --color=auto nginx
[root@localhost nginx-1.20.1]# 
[root@localhost nginx-1.20.1]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
        location /test {
            echo "test";
        }
[root@localhost conf]# cd /usr/src/nginx-1.21.3/
[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]# cd ..
[root@localhost src]# cp nginx-1.21.3/objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y

location区段

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

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

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

常用修饰符说明:

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


server {
        listen       8080;
        server_name  localhost;

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


[root@localhost conf]# nginx -s reload

如下内容就可正确匹配

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

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

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

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

[root@localhost conf]# nginx -s reload

如下内容就可正确匹配

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

如下内容则无法匹配

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

正则表达式模式匹配(区分大小写)
~:表示指定的正则表达式要区分大小写

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

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

如下内容就可正确匹配

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

如下内容则无法匹配

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

正则表达式模式匹配(不区分大小写)
~*:表示指定的正则表达式不区分大小写

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

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

如下内容就可正确匹配

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

如下内容则无法匹配

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

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

优先级次序
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

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

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

示例

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

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

 [root@localhost ~]# nginx -s reload

优先级测试

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

https配置

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

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

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

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

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

修改nginx文件

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

        ssl_certificate      /etc/nginx/ssl/test.crt;
        ssl_certificate_key /etc/nginx/ssl/test.key;

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

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

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

[root@localhost ~]# nginx -s reload
[root@localhost ~]# 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                 [::]:* 

在这里插入图片描述

nginx.conf配置文件案例

更改默认端口号以及进程数和指定特定配置文件
默认配置文件(/usr/local/nginx/conf/)nginx.conf文件内容

[root@localhost conf]# pwd
/usr/local/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;
.......
server {
        listen       80;
        server_name  localhost;

使用默认配置文件运行进程数如下
[root@localhost ~]# nginx
[root@localhost ~]#  ps -ef |grep nginx
root        9519       1  0 16:25 ?        00:00:00 nginx: master process nginx
nginx       9520    9519  0 16:25 ?        00:00:00 nginx: worker process
root        9666    1614  0 16:25 pts/1    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]# ll /opt/
总用量 12
-rw-r--r-- 1 root root 5231 1025 16:28 mime.types
-rw-r--r-- 1 root root 2656 1025 16:28 nginx.conf

[root@localhost conf]#  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进程最大可以打开的文件数
#user  nobody;
worker_processes 4;   #改为4个进程

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

#pid        logs/nginx.pid;
.......
server {
        listen       8080;  #更改端口号8080
        server_name  localhost;

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

[root@localhost opt]# ps -ef | grep nginx
root       31901       1  0 16:35 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx      31902   31901  0 16:35 ?        00:00:00 nginx: worker process
nginx      31903   31901  0 16:35 ?        00:00:00 nginx: worker process
nginx      31904   31901  0 16:35 ?        00:00:00 nginx: worker process
nginx      31905   31901  0 16:35 ?        00:00:00 nginx: worker process
root       33427    1614  0 16:36 pts/1    00:00:00 grep --color=auto nginx

在这里插入图片描述

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

配置访问规则

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

......
        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.200.128/32;   #允许本机访问
            deny   192.168.200.129/32;  #配置拒绝所有访问,上面配置的允许访问规则就会失效  
        }
......
[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# ss -anlt
State         Recv-Q        Send-Q               Local Address:Port                Peer Address:Port        
LISTEN        0             128                        0.0.0.0:8080                     0.0.0.0:*           
LISTEN        0             128                        0.0.0.0:22                       0.0.0.0:*           
LISTEN        0             128                              *:80                             *:*           
LISTEN        0             128                           [::]:22                          [::]:*       
—

在这里插入图片描述

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

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

使用另一台主机访问

[root@localhost ~]# curl  192.168.200.128
curl: (7) Failed connect to 192.168.153.128:80; 拒绝连接

基于用户认证

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

user_auth_file内容格式为:


username:password

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

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

示例

 // 安装httpd-tools
[root@localhost ~]# yum -y install httpd-tools

// 确保用户不存在
[root@localhost ~]# id syb
id: “syb”:无此用户

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

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

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

// 检测语法并重载配置文件
[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
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ss -anlt
State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port   
LISTEN   0        128              0.0.0.0:22            0.0.0.0:*      
LISTEN   0        128              0.0.0.0:80            0.0.0.0:*      
LISTEN   0        128                 [::]:22               [::]:*      

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

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

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

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

在这里插入图片描述

rewrite

rewrite作用

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

语法

rewrite regex replacement flag;

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

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

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

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

示例:

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

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

正常访问路径

http://192.168.200.128/imgs/R-C.jpg

在这里插入图片描述
将imgs文件夹名字修改为images

[root@localhost ~]# mv /usr/local/nginx/html/imgs/ /usr/local/nginx/html/images/
[root@localhost ~]# ls /usr/local/nginx/html/
50x.html  images  index.html  index.php

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


[root@localhost ~]# nginx -s reload

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

last和break组合使用示例

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

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

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

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

在这里插入图片描述
将break放到前面

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


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

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

[root@localhost ~]# nginx -s reload

在这里插入图片描述
常见的flag

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

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

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

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

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

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

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

if
语法:if (condition) {...}

应用场景:

  • server段
  • location段

常见的condition

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

举例

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

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

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

if ($slow) {
    limit_rate 10k;
}

if ($invalid_referer) {
    return 403;
}

基于浏览器实现分离案例

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

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

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

防盗链案例

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

开启状态页面

开启status:

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

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

在这里插入图片描述
访问状态页面的方式:http://server_ip/status

状态页面信息详解:

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

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

状态页面监控

环境说明

主机名ip职责
localhost192.168.200.128nginx、zabbix_agent
server192.168.200.152zabbix_server
在slave主机上安装zabbix_agentd
// 在nginx上安装zabbix_agentd
[root@localhost ~]# cd /usr/src/

// 将之前下载好的包传到虚拟机开始解压
[root@slave src]# tar xf zabbix-5.4.4.tar.gz 

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

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

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

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

写监控脚本

// 创建脚本目录
[root@localhost ~]# mkdir /scripts
[root@localhost ~]# cd /scripts/
[root@localhost scripts]# chown zabbix.zabbix /scripts/
[root@localhost scripts]# ll / | grep scripts
drwxr-xr-x    2 zabbix zabbix    6 1028 19:09 scripts
[root@localhost scripts]# touch status.sh
[root@localhost scripts]# chmod +x status.sh 
[root@localhost scripts]# vim status.sh 
#!/bin/bash

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

// 添加这一行
[root@localhost scripts]# vim /usr/local/etc/zabbix_agentd.conf
UserParameter=check_status[*],/bin/bash /scripts/status.sh $1

// 重启zabbix_agentd
[root@localhost scripts]# pkill zabbix_agentd 
[root@localhost scripts]# zabbix_agentd 
[root@localhost scripts]# 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              0.0.0.0:10050          0.0.0.0:*     
LISTEN   0        128                 [::]:22                [::]:*   

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

zabbix的web页面配置

添加主机在这里插入图片描述
添加监控项
在这里插入图片描述
添加触发器
在这里插入图片描述
添加表达式

这里为了显示出报警结果把触发值设为0
在这里插入图片描述
告警提示

其余两个监控项目、报警和上面一样添加就可以

反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力
nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了
但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFSMFS分布式共享存储
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 {							#此字段要写在server字段的前面
  ip_hash;
  server 127.0.0.1:9080 weight=5;				
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}


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

    }

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

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

server {
  location / {
    proxy_pass http://webservers;				#这里要和upstream段配置的域名一致
  }
}

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

环境说明

主机ip服务
LB192.168.200.159nginx
RS1192.168.200.131apache
RS2192.168.200.128lnmp

LB上安装nginx

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

/安装依赖环境
[root@LB ~]# yum -y install pcre-devel pcre gcc gcc-c++ openssl-devel zlib zlib-devel make vim wget openssl openssl-devel gd-devel

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

//下载nginx
[root@LB ~]# cd /usr/src/
[root@LB 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@LB src]# ls
debug  kernels  nginx-1.20.1.tar.gz

[root@LB src]# tar xf nginx-1.20.1.tar.gz 
[root@LB src]# cd nginx-1.20.1/
[root@LB nginx-1.20.1]# ./configure  --prefix=/usr/local/nginx  --user=nginx  --group=nginx  --with-debug  --with-http_ssl_module  --with-http_realip_module  --with-http_image_filter_module  --with-http_gunzip_module  --with-http_gzip_static_module  --with-http_stub_status_module  --http-log-path=/var/log/nginx/access.log  --error-log-path=/var/log/nginx/error.log
[root@LB nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

//使用service控制nginx
[root@LB 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@LB nginx-1.20.1]# systemctl daemon-reload 
[root@LB 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@LB 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                             [::]:*       

RS1上安装Apache

// 安装vim和wget
[root@RS1 ~]# yum -y install vim wget

//安装开发工具包
[root@RS1 ~]# yum groups mark install 'Development Tools' -y

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

// 安装依赖包
[root@RS1 ~]# yum -y install openssl-devel pcre-devel expat-devel libtool gcc gcc-c++ make

// 下载和安装httpd、apr以及apr-util
[root@RS1 src]# wget  https://mirrors.tuna.tsinghua.edu.cn/apache/httpd/httpd-2.4.49.tar.gz
[root@localhost src]# wget  https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.gz
[root@localhost src]# wget  https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util-1.6.1.tar.gz

// 解压软件包
[root@RS1 src]# tar xf apr-1.7.0.tar.gz 
[root@RS1 src]# tar xf apr-util-1.6.1.tar.gz 
[root@RS1 src]# tar xf httpd-2.4.49.tar.gz 

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

// 编译安装apr
[root@RS1 apr-1.7.0]# ./configure --prefix=/usr/local/apr
[root@RS1 apr-1.7.0]# make
[root@RS1 apr-1.7.0]# make install

// 编译安装apr-util
[root@RS1 apr-util-1.6.1]# ./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr/
[root@RS1 apr-util-1.6.1]# make && make install

// 编译安装httpd
[root@RS1 httpd-2.4.49]# ./configure --prefix=/usr/local/apache \
--enable-so \
--enable-ssl \
--enable-cgi \
--enable-rewrite \
--with-zlib \
--with-pcre \
--with-apr=/usr/local/apr \
--with-apr-util=/usr/local/apr-util/ \
--enable-modules=most \
--enable-mpms-shared=all \
--with-mpm=prefork
[root@RS1 httpd-2.4.49]# make && make install

// 环境变量
[root@RS1 ~]# which httpd
/usr/local/apache/bin/httpd
[root@RS1 ~]# echo 'export PATH=/usr/local/apache/bin:$PATH' > /etc/profile.d/httpd.sh
[root@RS1 ~]# source /etc/profile.d/httpd.sh
[root@RS1 ~]# ln -s /usr/local/apache/include /usr/include/apache
[root@RS1 ~]# ll /usr/include/
总用量 1760
-rw-r--r--.  1 root root   7456 312 2021 aio.h
-rw-r--r--.  1 root root   2031 312 2021 aliases.h
-rw-r--r--.  1 root root   1203 312 2021 alloca.h
-rw-r--r--.  1 root root   4350 312 2021 a.out.h
lrwxrwxrwx.  1 root root     25 923 15:56 apache -> /usr/local/apache/include  // 已经连接了
[root@RS1 ~]# vim /etc/man_db.conf
MANDATORY_MANPATH                       /usr/man
MANDATORY_MANPATH                       /usr/share/man
MANDATORY_MANPATH                       /usr/local/share/man
MANDATORY_MANPATH                       /usr/local/apache/man // 加上这一条

[root@RS1 ~]# vim /usr/local/apache/conf/httpd.conf
ServerName www.example.com:80   // 把这一行的注释取消掉

// 启动apache
[root@RS1 ~]# apachectl start
[root@RS1 ~]# ss -anlt
State     Recv-Q     Send-Q         Local Address:Port         Peer Address:Port    
LISTEN    0          128                  0.0.0.0:22                0.0.0.0:*       
LISTEN    0          128                        *:80                      *:*       
LISTEN    0          128                     [::]:22                   [::]:* 

// 设置开启自启
[root@RS1 ~]# cat /usr/lib/systemd/system/sshd.service > /usr/lib/systemd/system/httpd.service
[root@RS1 ~]# vim /usr/lib/systemd/system/httpd.service
[Unit]
Description=Httpd server daemon
After=network.target 

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

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

在RS2上安装LNMP
安装nginx

// 关闭防火墙和selinux
[root@RS2 ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@RS2 ~]# vim /etc/selinux/config 
SELINUX=disabled
[root@RS2 ~]# reboot 
[root@RS2 ~]# getenforce 0
Disabled

// 创建用户
[root@RS2 ~]# useradd -r -M -s /sbin/nologin nginx
[root@RS2 ~]# id nginx
uid=994(nginx) gid=991(nginx)=991(nginx)

// 安装依赖环境
[root@RS2 ~]# yum -y install epel-release
[root@RS2 ~]#  yum -y install http://mirror.centos.org/centos/8-stream/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm
[root@RS2 ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make  ncurses-devel cmake mariadb-devel ncurses-compat-libs  libxml2 libxml2-devel bzip2 bzip2-devel libcurl libcurl-devel libicu-devel libjpeg libjpeg-devel libpng libpng-devel openldap-devel  pcre-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel mhash mhash-devel php-mysqlnd libsqlite3x-devel oniguruma libzip-devel


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

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


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

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


// 启动nginx
[root@RS2 ~]# nginx
[root@RS2 ~]# 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@RS2 ~]# 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@RS2 ~]# systemctl daemon-reload
[root@RS2 ~]# systemctl enable --now  nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

安装MySQL

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

// 解压
[root@RS2 ~]# cd /usr/src/
[root@RS2 src]# ls
debug  kernels  mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz  nginx-1.20.1.tar.gz
[root@RS2 src]# tar xf mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz -C /usr/local/

// 软连接
[root@RS2 local]# mv mysql-5.7.34-linux-glibc2.12-x86_64/ mysql
[root@RS2 local]# chown -R mysql.mysql mysql/
[root@RS2 local]# ln -s /usr/local/mysql/include /usr/include/mysql

// 创建数据存放目录
[root@RS2 local]# mkdir /opt/data 
[root@RS2 local]# chown -R mysql.mysql /opt/data

// 配置环境变量
[root@RS2 local]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh 
[root@RS2 local]# . /etc/profile.d/mysql.sh

// 初始化
[root@RS2 local]# mysqld --initialize-insecure --user mysql --datadir /opt/data
2021-10-26T06:46:13.459861Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2021-10-26T06:46:13.592952Z 0 [Warning] InnoDB: New log files created, LSN=45790
2021-10-26T06:46:13.613937Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2021-10-26T06:46:13.669318Z 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: 6968897c-3628-11ec-b95c-000c29ba9d68.
2021-10-26T06:46:13.670365Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2021-10-26T06:46:14.690255Z 0 [Warning] CA certificate ca.pem is self signed.
2021-10-26T06:46:14.789009Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.

//编写配置文件
[root@RS2 local]# cat > /etc/my.cnf << EOF
> [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
> EOF

//使用service控制MySQL
[root@RS2 local]# cat > /usr/lib/systemd/system/mysqld.service << EOF
[Unit]
Description=Mysql server daemon
After=network.target sshd-keygen.target

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

[Install]
WantedBy=multi-user.target
basedir=/usr/local/mysql
datadir=/opt/data
EOF 

[root@RS2 src]#  vim /usr/local/mysql/support-files/mysql.server 
46 basedir=/usr/local   //修改这两行
47 datadir=/opt/data

// 启动服务
[root@RS2 local]# systemctl daemon-reload 
[root@RS2 local]# systemctl enable --now mysqld 
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@RS2 local]# 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          80                         *:3306                    *:*        
LISTEN     0          128                     [::]:22                   [::]:*   

// 设置密码
[root@RS2 ~]# yum -y install ncurses-compat-libs
[root@RS2 ~]# 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("syb123");
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> quit
Bye

安装PHP

// 解压
[root@RS2 src]# tar xf php-8.0.10.tar.xz -C /usr/local/
[root@RS2 src]# cd /usr/local/php-8.0.10/

// 编译安装
[root@RS2 nginx]# ./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 \ 
&& make && make install 

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

// 配置php
[root@RS2 php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm 
[root@RS2 php-8.0.10]# chmod +x /etc/init.d/php-fpm
[root@RS2 php-8.0.10]# cd /usr/local/php8 
[root@RS2 php8]# cd etc/ 
[root@RS2 etc]# cp php-fpm.conf.default  php-fpm.conf
[root@RS2 etc]# cd php-fpm.d/
[root@RS2 php-fpm.d]# cp www.conf.default www.conf 
[root@RS2 php-fpm.d]# ls
www.conf  www.conf.default

// 启动
[root@RS2 php-fpm.d]# service php-fpm start 
Starting php-fpm  done
[root@RS2 php-fpm.d]# 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            [::]:* 

nginx配置

// 配置网页文件
[root@RS2 nginx]# cd html/
[root@RS2 html]# vim index.php 
<?php
phpinfo();
?>
[root@RS2 html]# chown -R nginx.nginx index.php

// 修改配置文件
[root@RS2 nginx]# vim conf/nginx.conf
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $Document_Root$fastcgi_script_name;
            include        fastcgi_params;
        }
[root@RS2 ~]# nginx -s reload 

在这里插入图片描述

在LB上配置负载均衡

[root@LB ~]# vim /usr/local/nginx/conf/nginx.conf
upstream webservers {
        server 192.168.200.131;
        server 192.168.200.128;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

在浏览器上访问192.168.200.159
在这里插入图片描述
在这里插入图片描述
在LB上配置动静分离

[root@LB ~]# vim /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.200.131;   //设置静态访问
    }

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

    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@LB ~]# systemctl restart nginx.service 

在浏览器输入LB主机IP访问的是静态资源
在这里插入图片描述
在浏览器输入master主机IP+/index.php访问的是动态资源
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值