nginx一篇足已

nginx 官网
在这里插入图片描述
在这里插入图片描述

tengine官网

Tengine是由淘宝网发起的Web服务器项目。它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能和特性。它的目的是打造一个高效、安全的Web平台。

官网是中文的很友好

在这里插入图片描述


1. nginx简介

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

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

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

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

2. nginx的特性与优点
2.1 nginx的特性

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

  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多
2.2 nginx的优点
  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化
3. nginx的功能及应用类别
3.1 nginx的基本功能
  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
  • 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL
3.2 nginx的扩展功能
  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制
3.3 nginx的应用类别
  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
  • 使用nginx作反向代理、负载均衡、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用
4. nginx的模块与工作原理

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

4.1 nginx的模块分类

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

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

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

nginx模块从功能上分为三类,分别是:

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

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

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

具体的指令,请参考nginx官方文档

4.2 nginx的工作原理

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

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

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

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

在这里插入图片描述

下图展示了模块一次常规的HTTP请求和响应的过程

在这里插入图片描述

下图展示了基本的WEB服务请求步骤

在这里插入图片描述

5. nginx的安装与配置
5.1 nginx的安装
// 配置yum 源
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# rm -rf *
[root@localhost yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@localhost yum.repos.d]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo

// 清除缓存
[root@localhost yum.repos.d]# dnf clean all
0 files removed

// 建立缓存
[root@localhost yum.repos.d]# dnf makecache


//创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
[root@localhost ~]# id nginx
uid=995(nginx) gid=992(nginx) groups=992(nginx)

//安装依赖环境
[root@localhost ~]# dnf -y install  boost-devel --allowerasing pcre-devel openssl openssl-devel gd-devel  gcc gcc-c++ make

// 简单说明: 因下载 gcc 报错所以需要下载 boost-devel --allowerasing 如果你下载gcc 没有报错可以忽略

安装过程略....
[root@localhost ~]# yum -y groups mark install 'Development Tools'
Loaded plugins: product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Marked install: Development Tools

//创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
drwxr-xr-x. 2 nginx nginx 6 Aug 30 09:14 /var/log/nginx/

//下载nginx
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget https://nginx.org/download/nginx-1.22.0.tar.gz
--2022-08-30 09:16:13--  https://nginx.org/download/nginx-1.22.0.tar.gz
Resolving nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5702::6, ...
Connecting to nginx.org (nginx.org)|52.58.199.22|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1073322 (1.0M) [application/octet-stream]
Saving to: ‘nginx-1.22.0.tar.gz’

nginx-1.22.0.tar.gz 100%[================>]   1.02M   114KB/s    in 8.7s

2022-08-30 09:16:23 (121 KB/s) - ‘nginx-1.22.0.tar.gz’ saved [1073322/1073322]


//编译安装
[root@localhost src]# tar xf nginx-1.22.0.tar.gz  // 解压
[root@localhost src]# ls
debug  kernels  nginx-1.22.0  nginx-1.22.0.tar.gz
[root@localhost src]# cd nginx-1.22.0  // 进入解压目录
[root@localhost nginx-1.22.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.22.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
安装过程略....


// 简单说明: grep 'processor' /proc/cpuinfo | wc -l 这条命令时查看核心数
5.2 nginx安装后配置
//配置环境变量
[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 -antl
State   Recv-Q  Send-Q    Local Address:Port     Peer Address:Port  Process
LISTEN  0       128             0.0.0.0:80            0.0.0.0:*
LISTEN  0       128             0.0.0.0:22            0.0.0.0:*
LISTEN  0       128                [::]:22               [::]:*
6 nginx的配置文件详解

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

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

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

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

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

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

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

derective value1 [value2 ...];
  指令     参数;    必须分号结尾。

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value
6.2 用于调试、定位问题的配置参数
daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志。常用
6.2.1前台运行
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
user  nginx;
worker_processes  1;
daemon off;   // 添加
.... 省略N
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# nginx  // 启动nginx就会
    // 卡在这里
6.2.2使用 master模型
// 默认是 master 和 worker
[root@localhost ~]# ps -ef | grep nginx
root        1754       1  0 13:42 ?        00:00:00 nginx: master process nginx
nginx       1757    1754  0 13:42 ?        00:00:00 nginx: worker process
root        1762    1669  0 13:43 pts/1    00:00:00 grep --color=auto nginx
// master 用来接任务。worker 用来工作。

// 设置为 master 模型
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
user  nginx;
worker_processes  1;
master_process off;  // 添加
... 省略N
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# nginx -s reload

// 查看进程
[root@localhost ~]# ps -ef | grep nginx
root        1778       1  0 13:47 ?        00:00:00 nginx
root        1782    1669  0 13:48 pts/1    00:00:00 grep --color=auto nginx
// 就只有一个进程。谁启动的就谁进程
6.2.3配置错误日志
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
user  nginx;
worker_processes  1;

#error_log  logs/error.log;  // 前面注释取消 。 常用
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# nginx -t  // 检查语法是否有误
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost conf]# nginx -s reload  // 重新加载
[root@localhost ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid
[root@localhost ~]# tail /usr/local/nginx/logs/error.log  // 现在没有错误日志
[root@localhost ~]#

访问一个不存在的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jj9ERyv5-1662475421767)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662373198755.png)]


// 查看
[root@localhost ~]# tail /usr/local/nginx/logs/error.log
2022/09/05 18:19:48 [error] 1999#0: *1 open() "/usr/local/nginx/html/agan" failed (2: No such file or directory), client: 192.168.229.1, server: localhost, request: "GET /agan HTTP/1.1", host: "192.168.229.143"
// 推荐使用,用这种方式查看错误日志
// 解析:
日期 : 2022/09/05
没有这个文件或目录: /usr/local/nginx/html/agan" failed (2: No such file or directory)
从哪里访问的(客户端):  client: 192.168.229.1
服务端:本地  server: localhost
使用什么浏览器访问:GET(谷歌)
访问什么: /agan(访问根下面的agan)
使用的协议版本: HTTP/1.1(http1.1版本)
访问的主机IP: host: "192.168.229.143"

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

级别debug(高)–>emerg(低),级别越高信息越详细

位置详情级别详情
file(常用)指定文件的方式debug记录的信息非常详细,使用debug级别需要编译nginx时使用–with-debug,针对于高效解决错误问题,不常用
stderr屏幕里直接输出错误info
memory:size内存保存方式notice
syslog:server=address[parameter=value] (常用)错误日志记到另一台主机内warn
error(常用)显示网页错误的信息
crit
alert
emerg
6.3 正常运行必备的配置参数
user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024 (可设置10240/655350),配置在main字段处
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可
6.4 优化性能的配置参数
worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值
worker_processes  n;	 //启动n个worker进程,设置n时为了避免上下文切换,通常设置cpu总核心数-1或者总核心数。(留一个cpu或多个cup跑其它的进程,其它cpu均跑nginx)

#手动绑定cpu核心:(一个cpu指定一个进程)
worker_cpu_affinity 0001 0010;   		//2个cpu核心绑定
worker_cpu_affinity 0001 0010 0100;   		//3个cpu核心绑定
worker_cpu_affinity 0001 0010 0100 1000;   //4个cpu核心绑定
(二个cpu指定一个进程)
worker_cpu_affinity 0101 1010; 	//0101也就是第1、3个逻辑CPU上,1010就是第2、4个逻辑CPU上

#自动绑定cpu核心:
worker_cpu_affinity auto;  //自动绑定cpu核心

#减少工作进程中的计时器分辨率
timer_resolution interval;//减少工作进程中的计时器分辨率,从而减少gettimeofday()系统调
用的次数
如:timer_resolution 100ms;

worker_priority number;  //指定worker进程的nice值,范围在[-20,19],-20优先级最高
如:worker_priority -10;
6.5 事件相关的配置:event{}段中的配置参数
accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

event{}段中的配置

events {
    worker_connections  1024;    //进程连接的最大数
    accept_mutex on|off;      //工作进程将依次接受新连接,搭配lock_file字段使用
    use [epoll|rtsig|select|poll];  //指明使用的事件模型,一般默认nginx自行选择即可
}
lock_file logs/nginx.lock; //该字段配置在main字段处,告知锁定文件的路径

模拟生产环境中测试的30000并发量

// 查看核心数
[root@localhost ~]# ps -ef|grep nginx
root        1603       1  0 19:10 ?        00:00:00 nginx: master process nginx
nginx       1922    1603  0 19:12 ?        00:00:00 nginx: worker process
nginx       1923    1603  0 19:12 ?        00:00:00 nginx: worker process
nginx       1924    1603  0 19:12 ?        00:00:00 nginx: worker process
nginx       1925    1603  0 19:12 ?        00:00:00 nginx: worker process
root        1954    1929  0 19:13 pts/1    00:00:00 grep --color=auto nginx


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  4;   // 核心要对应你的虚拟机核心数

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

#pid        logs/nginx.pid;
events {
    worker_connections  8000;  // 连接
}
# 进程数为4个,8000*4=32000
# 一个worker进程可以处理8000千个并发量
# 4个CPU就可以处理32000个
[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


#测试并发用ab命令
[root@localhost ~]# dnf -y install  httpd-tools  #ab命令依赖包
[root@localhost ~]# ab -c 10 -n 30000 http://192.168.229.143/   //模拟10个用户访问30000个请求
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.229.143 (be patient)
Completed 3000 requests
Completed 6000 requests
Completed 9000 requests
Completed 12000 requests
Completed 15000 requests
Completed 18000 requests
Completed 21000 requests
Completed 24000 requests
Completed 27000 requests
Completed 30000 requests
Finished 30000 requests   //30000个请求完成
.... 省略N
Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      1
  98%      1
  99%      1
 100%      2 (longest request)
6.6 网络连接相关的配置参数
配置字段处:http, server,location
keepalive:长连接
keepalived:高可用
keepalive_timeout number;   //长连接的超时时间,默认为65秒
keepalive_requests number;  //长连接上能够允许请求的最大资源数,默认为1000
keepalive_disable [msie6|safari|none];   //指定UserAgent类型的浏览器禁止连接
tcp_nodelay on|off; 		//默认开启
tcp_nopush on|off;			//默认关闭
client_body_timeout number;  	//读取http请求报文body部分的超时时间
client_header_timeout number;  //读取http请求报文header部分的超时时间
send_timeout number;   //发送响应报文的超时时间
6.7 fastcgi的相关配置参数

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

location ~ \.php$ {
  root html;
  fastcgi_pass 127.0.0.1:9000;      //定义反向代理
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include fastcgi_params;
}
6.8 常需要进行调整的参数
  • worker_processes // 核心数
  • worker_connections // 连接
  • worker_cpu_affinity // 绑定CPU
  • worker_priority // 优先级
6.9 nginx作为web服务器时使用的配置:http{}段的配置参数

http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:

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

http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;
  server_name www.example.com;
  root "/vhosts/web";
}
# 配置文件下载
location /download {
  autoindex on;
  autoindex_exact_size off;
}

# 访问下载地址
# http://localhost/download

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

listen address[:port];
listen port;

server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符

当有多个server时,匹配顺序如下:

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

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

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

index file; 默认主页面

alias

[root@localhost ~]# mkdir /usr/local/nginx/html/hehe
[root@localhost ~]# echo 'hehe' > /usr/local/nginx/html/hehe/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 /hehe {  
            alias /usr/local/nginx/html/hehe;
            index index.html;
        }

        location / {
            root   html;
            index  index.html index.htm;
        }
[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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VGDWlLo9-1662475421768)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662385307221.png)]


[root@localhost ~]# mkdir -p /opt/myweb
[root@localhost ~]# echo 'hello world' > /opt/myweb/index.html
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

    location /hehe {
            alias /opt/myweb;
            index index.html;
        }
[root@localhost ~]# nginx -s reload

这时访问应该会访问到 hello world

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rM2s6sXG-1662475421770)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662385791152.png)]


错误页面

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

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html

配置错误页面

访问一个正常的网站时难免会出现404的情况,所以我们可以根据http响应的状态码来指定我们配置的错误页面,如:
error_page 404 =200 /404.html (访问到错误页面状态码404时,指定返回一个错误的页面)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j7A9P9VF-1662475421770)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662386135723.png)]


[root@localhost ~]# echo 'error_page' > /usr/local/nginx/html/404.html
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page  404 =200             /404.html;  // 注意 404 前面有空格200前面没有
[root@localhost ~]# nginx -s reload

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wvlHaK8D-1662475421771)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662386567552.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YIWLMSjM-1662475421772)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662386627523.png)]


log_format 定义日志格式

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
access_log  logs/access.log  main;

//注意:此处可用变量为nginx各模块内建变量
[root@localhost ~]# tail -1 /var/log/nginx/access.log
192.168.229.1 - - [05/Sep/2022:22:02:58 +0800] "GET /tkl HTTP/1.1" 200 11 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" " -"


remote_addr:远程地址 192.168.229.1
remote_user:远程用户(也就是那个用户访问) -
time_local:服务器本地的时间 05/Sep/2022:22:02:58 +0800
request:请求的资源  GET /tkl HTTP/1.1" 200 11 
status:状态码  200
body_bytes_sent: 发送主体字节数 11  (这个可以不要)
http_referer
http_user_agent:浏览器
http_x_forwarded_for: 从哪里跳转过来访问

// 制定日志格式
[root@localhost ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid  // 还没制定之前是两个文件,没有正常的日志文件
[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"';

    log_format  agan  '$remote_addr -  [$time_local] "$request" ' // 添加
                      '$status' ' "$http_user_agent" " $http_x_forwarded_for"'; // 添加

    access_log  logs/access.log agan;  // 添加agan
[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 ~]# ll /usr/local/nginx/logs/
total 8
-rw-r--r-- 1 root root    0 Sep  5 22:31 access.log  // 正常的日志问价没有内容,访问
-rw-r--r-- 1 root root 2071 Sep  5 22:29 error.log
-rw-r--r-- 1 root root    5 Sep  5 22:29 nginx.pid
// 访问网页,让其有数据
[root@localhost ~]# ll /usr/local/nginx/logs/
total 12
-rw-r--r-- 1 root root  184 Sep  5 22:33 access.log  // 已有数据
-rw-r--r-- 1 root root 2071 Sep  5 22:29 error.log
-rw-r--r-- 1 root root    5 Sep  5 22:29 nginx.pid
// 查看
[root@localhost ~]# tail -1 /usr/local/nginx/logs/access.log
192.168.229.1 -  [05/Sep/2022:22:33:27 +0800] "GET / HTTP/1.1" 304" Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" " -"

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

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

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

常用修饰符说明:

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

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

server {
  server_name www.example.com;
  location /abc {
    ......
  }
}

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

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/abc/

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

server {
  server_name www.idfsoft.com;
  location = /abc {
    ......
  }
}

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

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abc/abcde

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

server {
  server_name www.idfsoft.com;
  location ~ ^/abc$ {
  ......
  }
}

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

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/ABC
  • http://www.idfsoft.com/abcde

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

server {
  server_name www.idfsoft.com;
  location ~* ^/abc$ {
    ......
  }
}

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

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/ABC

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abcde

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

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

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

优先级次序如下:

( location = 路径 ) --> {( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 )} --> ( location 路径 )
6.10 访问控制

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

allow 192.168.1.1/32 172.16.0.0/16;
deny all;

设置访问控制

[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 / {
            root   html;
            index  index.html index.htm;
            allow 192.168.229.1/32;  // 允许192.168.229.1 
            deny all;  // 拒绝 所有
        }
    }
[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

访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dDqEfgUn-1662475421774)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662008394340.png)]


使用 192.168.229.143 访问

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

反过来设置,只允许 192.168.229.143 访问,拒绝所有

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            allow 192.168.229.143/32;
            deny all;
        }
    }
[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 

访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OwSAfz4T-1662475421774)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662008733703.png)]


使用 192.168.229.143 访问

[root@localhost ~]# curl 192.168.229.143
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>  // 访问成功
<style>
html { color-scheme: light dark; }
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>

6.11 基于用户认证
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
[root@localhost ~]# cat /usr/local/nginx/html/hehe/index.html
hehe
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

        location /hehe {
            auth_basic "欢迎阿干";  
            auth_basic_user_file "/usr/local/nginx/conf/.pass"; // 密码存放位置
            root   html;
            index  index.html index.htm;
        }
[root@localhost conf]# nginx -s reload


# 查询命令由哪个包提供的
[root@localhost ~]# dnf provides htpasswd
Last metadata expiration check: 1:20:39 ago on Tue 06 Sep 2022 08:08:50 AM CST.
httpd-tools-2.4.37-41.module_el8.5.0+977+5653bbea.x86_64 : Tools for use with the
                                                         : Apache HTTP Server
Repo        : AppStream
Matched from:
Filename    : /usr/bin/htpasswd
[root@localhost ~]# dnf -y install httpd-tools
[root@localhost ~]# which htpasswd
/usr/bin/htpasswd

// 用户agan,是访问页面用户
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass agan
New password:  // 密码
Re-type new password:  // 密码
Adding password for user agan
[root@localhost ~]# cat /usr/local/nginx/conf/.pass
agan:$apr1$K2RqQnZE$/slE0vk9ZqAnKBMNQzv9l.  // 密码是加密的

访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-patqkxU3-1662475421776)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662428349460.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BqeKkaU3-1662475421777)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662428373850.png)]


6.12 https配置

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

server {
  listen       443 ssl;
  server_name  www.idfsoft.com;
  ssl_certificate      /etc/nginx/ssl/nginx.crt;
  ssl_certificate_key  /etc/nginx/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;
  }
}
6.12.1 生成证书

openssl实现私有CA:

[root@localhost ~]# cd /etc/pki/
[root@localhost pki]# mkdir CA
[root@localhost pki]# cd CA/
[root@localhost CA]# mkdir private
[root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)   //在private目录下生成私钥文件
Generating RSA private key, 2048 bit long modulus (2 primes)
................+++++
..................................................................................+++++
e is 65537 (0x010001)
[root@localhost CA]# ls private/
cakey.pem
[root@localhost CA]# openssl rsa -in private/cakey.pem -pubout   //查看公钥,可以不做

CA生成自签署证书

[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365  //生成一个证书 有效日期为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) []:web.example.com  //域名
Email Address []:1@123.com  //邮箱

[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial


客户端(例如nginx服务器)生成密钥

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# mkdir ssl
[root@localhost conf]# cd 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]#

客户端生成证书签署请求

[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.example.com
Email Address []:1@123.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:  //直接回车就行
An optional company name []:  //直接回车就行
[root@localhost ssl]# ls
nginx.csr  nginx.key



CA签署客户端提交上来的证书

[root@localhost ssl]# pwd
/usr/local/nginx/conf/ssl
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Apr 17 02:06:04 2022 GMT
            Not After : Apr 17 02:06:04 2023 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = runtime
            commonName                = test.example.com
            emailAddress              = 1@123.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                91:A6:45:2F:19:E4:02:66:D5:DA:D5:9D:7E:1A:AE:53:50:8B:61:6B
            X509v3 Authority Key Identifier: 
                keyid:C4:8F:47:F7:95:86:84:55:D9:F3:3E:4B:55:FC:59:01:BE:F1:92:28

Certificate is to be certified until Apr 17 02:06:04 2023 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# rm -f nginx.csr //这个可以不要了
[root@localhost ssl]# ls
nginx.crt  nginx.key
//证书已生成好

// 在公司里只需要做这步
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  web.example.com;  // 域名

        ssl_certificate      /usr/local/nginx/conf/ssl/nginx.crt;  crt文件
        ssl_certificate_key  /usr/local/nginx/conf/ssl/nginx.key;  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
LISTEN         0              128                            0.0.0.0:443
LISTEN         0              128                            0.0.0.0:80
LISTEN         0              128                            0.0.0.0:22
LISTEN         0              128                               [::]:22

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U82KIrsS-1662475421779)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662432232102.png)]


6.13 开启状态界面

开启status:

location /status {
  stub_status {on | off};
  allow 172.16.0.0/16;
  deny all;
}

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

状态页面信息详解:

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AMjU5vsk-1662475421780)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662460522305.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OMNKgsJc-1662475421781)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662461091976.png)]


可以使用zabbix 监控状态页面的数值,监控哪个就用 awk 取出来大于多少就报警,发邮件

[root@localhost ~]# curl 192.168.229.143/status
Active connections: 1
server accepts handled requests
 4 4 4
Reading: 0 Writing: 1 Waiting: 0

// 取出accept 总共处理了多少个连接
[root@localhost ~]# curl -s 192.168.229.143/status|awk 'NR==3{print $1}'

// 取出 handlerd 成功创建多少握手
[root@localhost ~]# curl -s 192.168.229.143/status|awk 'NR==3{print $2}'

// 取出requests 总共处理了多少个请求
[root@localhost ~]# curl -s 192.168.229.143/status|awk 'NR==3{print $3}'

如果要监控哪一个数值就写到一个脚本里
6.14 rewrite

语法:rewrite regex replacement flag;,如:

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

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

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个路径,也可以是某个URL

常见的flag

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

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

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

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

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

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

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

演示

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

        location /images {  // 添加
            root html;
        }
[root@localhost ~]# nginx -s reload

// 创建相应的目录
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir images
[root@localhost html]# cd images/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0qLXGv3e-1662475421782)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662463010863.png)]


// 重命名为 1.jpg
[root@localhost images]# mv hdImg_3c00be50e946f68595ce7638592a88121605591655116.jpg 1.jpg
[root@localhost images]# ls
1.jpg

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HhBwJVIh-1662475421783)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662463136885.png)]


这时把 images 名字修改了imgs了,访问不了
[root@localhost html]# mv images imgs
//  但是呢,以前怎么访问还是怎么访问。我不想改为imgs

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IVSkqWga-1662475421784)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662463731364.png)]


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

        location /images {
           rewrite ^/images/(.*\.jpg)$ /imgs/$1 break; // URL 重写
        }
[root@localhost ~]# nginx -s reload
// 老用户还是可以用老方法访问。新用户可以告诉他新的访问方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fYmSA24e-1662475421784)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662463807313.png)]


配置指向某一个位置
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 location / {
            root   html;
            index  index.html index.htm;
        }

        location /images {
            rewrite ^/images/(.*\.jpg)$ https://img2.baidu.com/it/u=2371356524,1751901313&fm=253&fmt=auto&app=138&f=JPG?w=658&h=370  break;
        }
[root@localhost ~]# nginx -s reload

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U4TWb69Y-1662475421785)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662464286499.png)]


资源在本地或者在网上都行


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QZel4pMc-1662475421786)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662465396669.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OsqZ0jp8-1662475421787)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662465442838.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PffTpqh9-1662475421788)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662465530414.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UbHvoutj-1662475421789)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662465578824.png)]

6.15 if

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

应用场景:

  • server段
  • location段

常见的condition

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

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

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

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

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

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

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

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

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

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}
6.15.2 防盗链案例
location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.example.com/403.html;
  }
}
6.16 反向代理与负载均衡

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

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

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

Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache

如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......

nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内

upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:

upstream idfsoft.com {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

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

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

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

系统平台IP服务主机名
centos8192.168.229.143nginxnode1
centos8192.168.229.177nginxnode2
centos8192.168.229.179httpdnode3

// 下载 nginx
[root@node2 ~]# dnf -y install nginx
[root@node2 ~]# echo 'node2' > /usr/share/nginx/html/index.html
[root@node2 ~]# systemctl start nginx


// 下载httpd
[root@node3 ~]# dnf -y install httpd
[root@node3 ~]# echo 'node3' > /var/www/html/index.html
[root@node3 ~]# systemctl status httpd

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qxHADvoL-1662475421790)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662471602150.png)]


配置负载均衡

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WHzfOsfN-1662475421792)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662472240529.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-53Vv7rV4-1662475421792)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662472598722.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dUCZrIeC-1662475421793)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662472906742.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RQ0KMtNw-1662475421795)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662473065134.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WXLmunXw-1662475421795)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662473382824.png)]


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uvd9jkYN-1662475421796)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662473463302.png)]


动静配置的方法

    upstream dynamic {     // 动态
        server 192.168.229.177;  // 动态IP
        server 192.168.229.179;
    }

    upstream static {      // 静态
        server 192.168.229.180;   // 静态IP
        server 192.168.229.181;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://static;  // 引用静态
        }

        location ~ \.php$ {
            proxy_pass   http://dynamic;  // 引用动态
        }

7. 配置三种不同虚拟主机

虚拟主机:
虚拟主机有三类:

  • 相同IP不同端口
  • 不同IP相同端口
  • 相同IP相同端口不同域名

7.1 相同IP不同端口
[root@localhost ~]# cd /opt/
[root@localhost opt]# mkdir myweb
[root@localhost opt]# echo  'hello world' > myweb/index.html
[root@localhost opt]# cat myweb/index.html
hello world

## 添加下面
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       8080;
        server_name  localhost;

        location / {
            root   /opt/myweb;
            index  index.html index.htm;
        }
    }
[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 
// 看到successful 表示正常
[root@localhost ~]# nginx -s reload  ## 刷新,让其生效

访问 192.168.229.143

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1KQxq1La-1662475421797)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1661997492747.png)]


访问 192.168.229.143:8080

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ehUTsYGX-1662475421797)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1661997578703.png)]


7.2 不同IP相同端口
[root@localhost ~]# ip addr add 192.168.229.190/24 dev ens160  // 添加IP
[root@localhost ~]# ip addr show ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:cd:9f:89 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.143/24 brd 192.168.229.255 scope global dynamic noprefixroute ens160
       valid_lft 1650sec preferred_lft 1650sec
    inet 192.168.229.190/24 scope global secondary ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fecd:9f89/64 scope link noprefixroute
       valid_lft forever preferred_lft forever


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen      192.168.229.190:80;
        server_name  localhost;

        location / {
            root   /opt/myweb;
            index  index.html index.htm;
        }
    }
[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

访问 192.168.229.143

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KyoVVdXl-1662475421798)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1661998657318.png)]


访问 192.168.229.190

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l7NXDmYV-1662475421798)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1661998712850.png)]


7.3 相同IP相同端口不同域名
    server {
        listen     80;
        server_name  test.example.com;  // 域名

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


    server {
        listen       80;
        server_name  web.example.com;  // 域名

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

[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

访问 web.example.com

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ChxYgnO2-1662475421799)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662002418902.png)]


访问 test.example.com

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZLu0K8JV-1662475421801)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662002452167.png)]


8. 升级版本

源码升级软件或添加功能模块的步骤:

  1. 准备升级包或功能包
  2. 获取升级前的版本的编译参数
  3. 解压新版本,使用 configure 进行配置,配置时加上升级前版本的编译参数,然后添加新功能的模块
  4. 编译(禁止执行 make install 安装)
  5. 使用新程序和老版本配置文件启动新版本
  6. 如果第5步成功,则备份老版本的程序并同时复制新版本程序覆盖老版本并重启
  7. 验证
// 下载 echo 模块。添加模块的功能跟升级是一样的
[root@localhost src]# git clone https://github.com/openresty/echo-nginx-module.git
// 下载新版本,用来升级
[root@localhost src]# wget https://nginx.org/download/nginx-1.22.0.tar.gz
[root@localhost src]# ls
debug
echo-nginx-module-0.62
kernels
nginx-1.20.2
nginx-1.20.2.tar.gz
nginx-1.22.0.tar.gz

// 解压新版本,进到新版本目录里
[root@localhost src]# tar xf echo-nginx-module-0.62.tar.gz

// 把之前编译的参数跟添加echo 模块的功能
[root@localhost nginx-1.22.0]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log


[root@localhost src]# cd  nginx-1.22.0
[root@localhost nginx-1.22.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 --add-module=../echo-nginx-module-0.62

// make 。make 完成后会产生主程序
[root@localhost nginx-1.22.0]# ls objs/
addon  autoconf.err  Makefile  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  src

[root@localhost nginx-1.22.0]# make
// 编译完成后看到新版本的主程序  nginx
[root@localhost nginx-1.22.0]# ls objs/
addon  autoconf.err  Makefile  nginx  nginx.8  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  ngx_modules.o  src

// 先停掉老版本,接着启动新版本。这样时间上会一致。
[root@localhost nginx-1.22.0]# nginx -s stop;./objs/nginx -c /usr/local/nginx/conf/nginx.conf

// 一步到位。数据一致
[root@localhost nginx-1.22.0]# mv /usr/local/nginx/sbin/nginx{,.bak};\cp objs/nginx /usr/local/nginx/sbin/;nginx -s stop;nginx

[root@localhost ~]# ps -ef|grep nginx
root       36198       1  0 23:30 ?        00:00:00 nginx: master process nginx
nginx      36199   36198  0 23:30 ?        00:00:00 nginx: worker process
root       36201    1670  0 23:30 pts/0    00:00:00 grep --color=auto nginx

// 查看是否已有echo 模块
[root@localhost ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log--add-module=../echo-nginx-module-0.62  // 说明升级成功

验证

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dHc1m41K-1662475421804)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662391878657.png)]


添加新模块功能

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l9gX2KcJ-1662475421805)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662422883048.png)]


如果只添加新模块就用这种方式。如果升级跟添加新模块就用上面的

[root@localhost src]# tar xf echo-nginx-module-0.62.tar.gz  // 解压
[root@localhost src]# ls
debug  kernels  nginx-1.22.0  nginx-1.22.0.tar.gz 
echo-nginx-module-0.62  echo-nginx-module-0.62.tar.gz
// 查看安装前的参数
[root@localhost ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

[root@localhost ~]# cd /usr/src/
[root@localhost src]# ls
debug  kernels  nginx-1.22.0  nginx-1.22.0.tar.gz
echo-nginx-module-0.62  echo-nginx-module-0.62.tar.gz
//  nginx-1.22.0移到/opt/  的下面

[root@localhost src]# mv nginx-1.22.0 /opt/
[root@localhost src]# ls
debug  kernels  nginx-1.22.0.tar.gz
echo-nginx-module-0.62  echo-nginx-module-0.62.tar.gz
// 解压
[root@localhost src]# tar xf nginx-1.22.0.tar.gz
[root@localhost src]# ls
debug  kernels  nginx-1.22.0  nginx-1.22.0.tar.gz
echo-nginx-module-0.62  echo-nginx-module-0.62.tar.gz
// 进到解压目录
[root@localhost src]# cd nginx-1.22.0
[root@localhost nginx-1.22.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 --add-module=../echo-nginx-module-0.62  // 添加模块

// 编译
[root@localhost nginx-1.22.0]# make
...省略N

// 两个文件不相同
[root@localhost nginx-1.22.0]# ll objs/nginx
-rwxr-xr-x 1 root root 6697912 Sep  6 08:14 objs/nginx
[root@localhost nginx-1.22.0]# ll /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 6192528 Sep  1 09:13 /usr/local/nginx/sbin/nginx

// 备份原来的nginx 主程序,如果把新的主程序覆盖到原来的主程序的过程出现问题。就回滚。
[root@localhost nginx-1.22.0]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost nginx-1.22.0]# ll /opt/nginx
-rwxr-xr-x 1 root root 6192528 Sep  6 08:17 /opt/nginx

// 停止,再复制,再启动。一气呵成
[root@localhost nginx-1.22.0]# nginx -s stop;\cp objs/nginx /usr/local/nginx/sbin/;nginx

// 查看是否一样
[root@localhost nginx-1.22.0]# ll objs/nginx
-rwxr-xr-x 1 root root 6697912 Sep  6 08:14 objs/nginx
[root@localhost nginx-1.22.0]# ll /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 6697912 Sep  6 08:20 /usr/local/nginx/sbin/nginx
// 一样的大小

// 如果复制过去有问题,那就回滚。把原来的文件覆盖。

[root@localhost ~]# ss -antl
State          Recv-Q         Send-Q                   Local Address:Port
LISTEN         0              128                            0.0.0.0:80
LISTEN         0              128                            0.0.0.0:22
LISTEN         0              128                               [::]:22

[root@localhost ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log--add-module=../echo-nginx-module-0.62

9. 常用修饰符案例

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

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

        location /tkl {
           echo 'agan1';
        }

        location = /tkl {
           echo 'agan2';
        }

[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  // 刷新程序
// 访问到agn2 因为他的优先级高与agan1

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CF2Rtndp-1662475421806)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662425694998.png)]


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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2xHyjexI-1662475421806)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662426705851.png)]


~*:正则表达式模式匹配,不区分大小写

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4l2GD2TS-1662475421806)(D:/Markdown/%E5%8D%9A%E5%AE%A2/%E7%A0%B4%E8%A7%A3%E5%AF%86%E7%A0%81/1662426818372.png)]


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值