nginx,nginx由俄罗斯的


nginx


目录
  • nginx
    • nginx简介
    • nginx的特性与优点
    • nginx的扩展功能
    • nginx的应用类别
    • nginx的模块分类
    • nginx的工作原理
    • 源码安装nginx
    • nginx平滑升级
    • nginx配置文件
      • nginx.conf配置详解
      • 用于调试、定位问题的配置参数
      • 正常运行必备的配置参数
      • 优化性能的配置参数
      • 网络连接相关的配置参数
      • fastcgi的相关配置参数
      • nginx作为web服务器时使用的配置:http{}段的配置参数
      • location区段,通过指定模式来与客户端请求的URI相匹配
    • Nginx访问控制
    • nginx用户认证
    • https配置
    • Nginx启用状态页面
    • zabbix监控Nginx状态
    • rewrite
    • if

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是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

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

优点
高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数

内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)

配置文件非常简单:风格跟程序一样通俗易懂

成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币

支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
访问这个http://www.baidu.com/
会变成这个https://www.baidu.com/

内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问

节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头,在网络上传输时,自动压缩,到了对面自动解压

稳定性高:用于反向代理,宕机的概率微乎其微

模块化设计:模块可以动态编译

动态编译:编译时只编译主程序,其他的额外功能编译成模块,使用的时去加载,主程序比较小
静态编译:在一开始编译将所有的功能编译到主程序中,主程序文件比较大
外围支持好:文档全,二次开发和模块较多

支持热部署:可以不停机重载配置文件,配置文件修改之后让它生效,不需要重启服务

支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

同步,可以理解为在执行完一个函数或方法之后,一直等待系统返回值或消息,这时程序是出于阻塞的,只有接收到返回的值或消息后才往下执行其他的命令,同步,就是实时处理(如打电话)
同步在一定程度上可以看做是单线程,这个线程请求一个方法后就待这个方法给他回复,否则他不往下执行
异步,执行完函数或方法后,不必阻塞性地等待返回值或消息,只需要向系统委托一个异步过程,那么当系统接收到返回值或消息时,系统会自动触发委托的异步过程,从而完成一个完整的流程。异步,就是分时处理(如收发短信)
异步在一定程度上可以看做是多线程的,请求一个方法后,就不管了,继续执行其他的方法
内存映射:有一份数据在内存中放着,有多个位置需要使用,没有内存映射,同一份数据要生成多份,有的话,可以指向数据存放位置中

正向代理为客户端服务
正向代理

正向代理时,由客户端发送对某一个目标服务器的请求,代理服务器在中间将请求转发给该目标服务器,目标服务器将结果返回给代理服务器,代理服务器再将结果返回给客户端。
使用正向代理时,客户端是需要配置代理服务的地址、端口、账号密码(如有)等才可使用的。
①租客(用户)、②中介(代理服务器)、③房东(国外网站,目标服务器)
租房子一般会很难找到房东(目标服务器),但是房东却会把房屋信息、钥匙给中介(代理服务器)。对于房东(目标服务器)来说,他可能不知道要租他房子的人(用户)是谁,他只知道中介(代理服务器)在联系他。
引入中介(代理服务器)其实也就是因为租客(用户)无法直接联系房东(目标服务器)

反向代理为服务器端服务
反向代理,nginx,负载均衡

服务器根据客户端的请求,从其关系的一组或多组后端服务器(如Web服务器)上获取资源,然后再将这些资源返回给客户端,客户端只会得知代理服务器的IP地址,而不知道在代理服务器后面的服务器集群的存在。
反向代理整个流程:由客户端发起对代理服务器的请求,代理服务器在中间将请求转发给某一个服务器,服务器将结果返回给代理服务器,代理服务器再将结果返回给客户端。
还是租房子:假如没有中介:只有①房东、②二房东(放房东对外租房)、③租客,Web开发中就经常有这种反向代理:客户端(租客)发送请求到负载均衡服务器(二房东),负载均衡服务器(二房东)再把请求转发给一台真正的服务器(房东)来执行,再把执行结果返回给客户端(租客)

透明代理

透明代理也叫做内网代理(inline proxy)、拦截代理(intercepting proxy)以及强制代理(force proxy),所谓透明,即代理对客户端具有无感知性,即不需要客户端进行额外配置。
透明代理和正向代理基本相似,甚至是透明代理可以作为正向代理的一种。
透明代理技术经常作为一种备选模式存在,如在防火墙中作为策略,对部分流量进行过滤拦截;一般公司内的上网行为管理系统也是透明代理的应用。

nginx的扩展功能

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

nginx的应用类别

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

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

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

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

用户先找到nginx,nginx交给master,master生成很多worker,worker包括很多模块,核心功能

worker查看信息是本地处理还是其他人处理。如果是本地处理直接找到硬盘缓存下来处理,下次再请求静态资源直接将缓存资源给他
如果是动态的就通过fastcgi交给应用服务器,应用服务器处理完返还给他
本地缓存没有mencache强大,所以放入mencache中,如果有请求,直接查看mencache缓存

mencache没有持久化

中间的master和proxy是nginx,前端,做负载均衡,worker首先查看资源是动态的还是静态的,是静态的用http交给web server直接处理,处理完成后

webserver 后端做rs
工作方式
在工作方式上,Nginx分为单工作进程和多工作进程两种模式。在单工作进程模式下,除主进程外,还有一个工作进程,工作进程是单线程的;在多工作进程模式下,每个工作进程包含多个线程。Nginx默认为单工作进程模式。

Nginx在启动后,会有一个master进程和多个worker进程。

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

用户通过http发出请求,nginx内核建立一个handlers处理器模块,用模块处理,处理完之后,用过滤器进行过滤,得到结果响应用户

处理器模块还会用到代理模块

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

通过用户的浏览器跟服务器的nginx建立连接,建立连接用的是tcp/ip协议

建立连接通道之后可以发送请求,nginx收到请求,处理请求,访问资源(资源存放在硬盘上),取出资源之后构建响应,发送响应,然后将所有的事件记录下来(日志)

源码安装nginx

nginx官网
在官网里面找Stable version(稳定版本)
此处我安装的nginx-1.20.2

[root@localhost ~]# systemctl stop firewalld.service  //关闭防火墙
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# setenforce 0
[root@localhost ~]# systemctl disable --now firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
//创建系统用户nginx
[root@localhost ~]# dnf -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ wget make
//安装依赖包
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
//创建日志存放目录
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget http://nginx.org/download/nginx-1.20.2.tar.gz    //下载nginx
[root@localhost src]# ls
debug  kernels  nginx-1.20.2.tar.gz
[root@localhost src]# tar xf nginx-1.20.2.tar.gz 
[root@localhost src]# cd nginx-1.20.2/
[root@localhost nginx-1.20.2]# ./configure \   //进行编译
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@localhost nginx-1.20.2]# make -j $(grep 'processor' /proc/cpuinfo | wc -l)
//统计系统里面有几个cpu。然后进行安装
[root@localhost nginx-1.20.2]# ls
CHANGES  CHANGES.ru  LICENSE  Makefile  README  auto  conf  configure  contrib  html  man  objs  src
[root@localhost nginx-1.20.2]# ls objs/   //编译存放的地方
Makefile      nginx    ngx_auto_config.h   ngx_modules.c  src
autoconf.err  nginx.8  ngx_auto_headers.h  ngx_modules.o
[root@localhost nginx-1.20.2]# file objs/nginx
objs/nginx: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=78fd7100a678e28a8c2fa27612bca3c7e6411f9a, with debug_info, not stripped
//ELF主程序文件
[root@localhost nginx-1.20.2]# make install 
//安装
[root@localhost nginx-1.20.2]# cd /usr/local/nginx/
[root@localhost nginx]# ls
conf  html  logs  sbin
[root@localhost nginx]# /usr/local/nginx/sbin/nginx  //开启ngix
[root@localhost nginx]# ss -antl   //查看80端口
State      Recv-Q     Send-Q          Local Address:Port           Peer Address:Port     Process     
LISTEN     0          128                   0.0.0.0:80                  0.0.0.0:*                    
LISTEN     0          128                   0.0.0.0:22                  0.0.0.0:*                    
LISTEN     0          128                      [::]:22                     [::]:*    
[root@localhost nginx]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
//配置环境变量
[root@localhost nginx]# source /etc/profile.d/nginx.sh
//使其生效
[root@localhost nginx]# cd
[root@localhost ~]# which nginx  //现在就是可以直接用nginx启动服务
/usr/local/nginx/sbin/nginx
[root@localhost ~]# nginx -s stop  //停止服务
[root@localhost ~]# ss -antl
State      Recv-Q     Send-Q          Local Address:Port           Peer Address:Port     Process     
LISTEN     0          128                   0.0.0.0:22                  0.0.0.0:*                    
LISTEN     0          128                      [::]:22                     [::]:*                    
[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                     [::]:*  
//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}                                  

访问:

将其添加到systemd服务里面

[root@localhost ~]# cp /usr/lib/systemd/system/sshd.service /usr/lib/systemd/system/nginx.service
[root@localhost ~]# vim /usr/lib/systemd/system/nginx.service
[root@localhost ~]# 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@localhost ~]# nginx -s stop //先停止nginx
[root@localhost ~]# systemctl daemon-reload 
//加载配置
[root@localhost ~]# systemctl enable --now nginx.service //设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@localhost ~]# systemctl enable --now nginx.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@localhost ~]# systemctl status nginx.service  //查看状态
● nginx.service - nginx server daemon
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2022-10-12 21:16:18 CST; 47s ago
  Process: 76036 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
 Main PID: 76037 (nginx)
    Tasks: 2 (limit: 12221)
   Memory: 2.5M
   CGroup: /system.slice/nginx.service
           ├─76037 nginx: master process /usr/local/nginx/sbin/nginx
           └─76038 nginx: worker process

Oct 12 21:16:18 localhost systemd[1]: Starting nginx server daemon...
Oct 12 21:16:18 localhost systemd[1]: Started nginx server daemon.
[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                     [::]:*                    

访问:

nginx平滑升级

平滑升级流程
获取老版本的编译信息
获取新版本安装包或者功能包
配置新版本或功能,配置时加上老版本的编译信息和新版本或功能
编译,编译后不执行安装操作
备份老版本程序
停止老版本程序或进程
将新版本复制到老版本所在位置替换老版本
启动新版本

//此处接着前面的源码安装nginx进行操作

[root@localhost ~]# 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 ~]# dnf -y install git //获取新版本安装包和功能包(功能包可以git克隆)
[root@localhost ~]# cd /usr/local/src/
[root@localhost src]# wget https://nginx.org/download/nginx-1.22.0.tar.gz    //下载新版本的包
[root@localhost src]# git clone https://gitee.com/wujunze/nginx_module_echo.git
Cloning into 'nginx_module_echo'...
remote: Enumerating objects: 80, done.
remote: Total 80 (delta 0), reused 0 (delta 0), pack-reused 80
Unpacking objects: 100% (80/80), 14.32 KiB | 666.00 KiB/s, done.
[root@localhost src]# ls
nginx-1.22.0.tar.gz  nginx_module_echo
[root@localhost src]# tar -xf nginx-1.22.0.tar.gz
[root@localhost src]# cd nginx-1.22.0/
[root@localhost nginx-1.22.0]# ./configure \    //配置时,老版本的配置加上新加的模块,用--add-module=模块目录参数
> --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 \
> --add-module=../nginx_module_echo
[root@localhost nginx-1.22.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l)    //开始安装,此时不要先安装
[root@localhost nginx-1.22.0]# objs/nginx -v
nginx version: nginx/1.22.0
[root@localhost nginx-1.22.0]# \cp /usr/local/nginx/sbin/nginx{,-bak};pkill nginx;\cp objs/nginx /usr/local/nginx/sbin/;systemctl start nginx    //替换版本,使用一条命令解决
[root@localhost nginx-1.22.0]# nginx -v  //此时已经替换为新版本,服务也启动了   
nginx version: nginx/1.22.0
[root@localhost nginx-1.22.0]# 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                     [::]:*                    

访问:

nginx配置文件

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

配置文件 作用
nginx.conf nginx的基本配置文件
mime.types MIME类型关联的扩展文件
fastcgi.conf 与fastcgi相关的配置
proxy.conf 与proxy相关的配置
sites.conf 配置nginx提供的网站,包括虚拟主机
[root@localhost nginx]# pwd
/usr/local/nginx
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]# ls logs/
nginx.pid
[root@localhost nginx]# ls sbin/nginx   //主程序
sbin/nginx
[root@localhost nginx]# file sbin/nginx    //ELF(主程序)
sbin/nginx: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=146c123f448d84a21258affd355418734db34b42, with debug_info, not stripped
[root@localhost nginx]# ls html/  //网站
50x.html  index.html

[root@localhost nginx]# cd conf/     //主配置文件
[root@localhost conf]# ls
fastcgi.conf            koi-utf             nginx.conf           uwsgi_params
fastcgi.conf.default    koi-win             nginx.conf.default   uwsgi_params.default
fastcgi_params          mime.types          scgi_params          win-utf
fastcgi_params.default  mime.types.default  scgi_params.default
[root@localhost conf]# ls nginx.conf
nginx.conf

查看帮助以及nginx的参数

[root@localhost ~]# nginx -h
nginx version: nginx/1.22.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/local/nginx/)
  -e filename   : set error log file (default: logs/error.log)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file
[root@localhost ~]# nginx -v   //查看版本
nginx version: nginx/1.22.0
[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 --add-module=../nginx_module_echo
选项:
-h:这个帮助
-v:显示版本并退出
-V:显示版本并配置选项,然后退出
-t:测试配置并退出
-T:测试配置,下载并退出
-q:在配置测试时抑制非错误消息
向主进程发送信号:停止,退出,重新打开,重新加载
设置前缀路径(默认为/usr/local/nginx/)
-e filename:设置错误日志文件(默认为/var/log/nginx/error.log)
-c filename:设置配置文件(默认为conf/nginx.conf),将配置文件copy一份,修改新的配置文件,使用-c指定配置文件
-g directives:将全局指令从配置文件中设置出来

查看日志

[root@localhost ~]# cd /usr/local/nginx/
[root@localhost nginx]# tail -4 /var/log/nginx/access.log 
192.168.222.1 - - [10/Oct/2022:21:26:01 +0800] "GET / HTTP/1.1" 200 615 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37"
192.168.222.1 - - [10/Oct/2022:21:26:01 +0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.222.250/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37"
192.168.222.1 - - [10/Oct/2022:21:52:36 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37"

[root@localhost nginx]# tail -1f /var/log/nginx/access.log 
192.168.222.1 - - [10/Oct/2022:21:52:36 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37"
//f一直查看

nginx.conf配置详解

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

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

derective value1 [value2 ...];
支持使用变量:
 
内置变量:模块会提供内建变量定义
自定义变量:set var_name value

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

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:size
debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项
info
notice
warn
error
crit
alert
emer

正常运行必备的配置参数

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

优化性能的配置参数

worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值
6.5 事件相关的配置:event{}段中的配置参数
accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

网络连接相关的配置参数

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长

fastcgi的相关配置参数

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

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

nginx作为web服务器时使用的配置:http{}段的配置参数

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

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

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

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

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

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

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

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

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

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

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

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

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

log_format 定义日志格式

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
access_log  logs/access.log  main;
 
//注意:格式名main可自己定义,但要一一对应,另外此处可用变量为nginx各模块内建变量

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

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

//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:

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

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

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

优先级如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

没添加任何修饰符则按先后顺序

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 server {
        listen       80;
        server_name  localhost;  //在这个下面添加下面配置
        location / {              
            echo 'tushanbu';     
        }                         

        location /xbz {
            echo 'xbz';
        }

        location /tsb {
            echo 'tsb';
        }
注释下面的
location / {
            root   html;
            index  index.html index.htm;
        }

[root@localhost ~]# systemctl reload nginx.service 
//重新加载配置
[root@localhost ~]# curl 192.168.222.250
tushanbu
[root@localhost ~]# curl 192.168.222.250/xbz
xbz
[root@localhost ~]# curl 192.168.222.250/tsb
tsb

=精确匹配

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  localhost;
        location / {
            echo 'tushanbu';
        }

        location /tsb {      //修改
            echo 'xbz';
        }

        location = /tsb {  //修改
            echo 'tsb';
        }

[root@localhost ~]# systemctl reload nginx.service 
//重新加载配置
[root@localhost ~]# curl 192.168.222.250/tsb
tsb
//可看见相同的目录,等于号的级别大

添加 ~ 为区分大小写

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  localhost;
        location / {
            echo 'tushanbu';
        }

        location /tsb {
            echo 'xbz';
        }

        location ~ /tsb {   //修改
            echo 'tsb';
        }
[root@localhost ~]# systemctl reload nginx.service 
//重新加载配置
[root@localhost ~]# curl 192.168.222.250/TSB
tushanbu      //因为区分大小写找不到资源所以输出的是默认tushanbu 
[root@localhost ~]# curl 192.168.222.250/tsb
tsb

~ 为不区分大小写*

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  localhost;
        location / {
            echo 'tushanbu';
        }

        location /tsb {
            echo 'xbz';
        }

        location ~* /tsb {    //修改
            echo 'tsb';
        }
[root@localhost ~]# systemctl reload nginx.service 
//重新加载配置
[root@localhost ~]# curl 192.168.222.250/TSB
tsb
[root@localhost ~]# curl 192.168.222.250/tsb
tsb
//因为不区分大小写所以TSB和tsb都能访问到tsb

^~ 为前缀匹配

server {
        listen       80;
        server_name  localhost;
        location / {
            echo 'tushanbu';
        }

        location ^~/tsb {    //修改
            echo 'xbz';
        }

        location ~ /tsb {       //修改
            echo 'tsb';
        }
[root@localhost ~]# systemctl reload nginx.service 
//重新加载配置
[root@localhost ~]# curl 192.168.222.250/tsb
xbz
//前缀匹配如果访问到了资源则停止搜索

Nginx访问控制

用于http, server, location, limit_except段
allow:设定允许哪台或哪些主机访问
deny:设定禁止哪台或哪些主机访问

[root@localhost html]# cd
[root@localhost ~]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp  fastcgi_temp  proxy_temp  scgi_temp
conf              html          logs        sbin        uwsgi_temp
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# echo "hello lnh" >index.html //可以向要网站里面编辑内容
[root@localhost html]# systemctl restart nginx.service
//重启服务 
[root@localhost html]# ss -antl
State      Recv-Q     Send-Q          Local Address:Port           Peer Address:Port     Process     
LISTEN     0          128                   0.0.0.0:80                  0.0.0.0:*                    
LISTEN     0          128                   0.0.0.0:22                  0.0.0.0:*                    
LISTEN     0          128                      [::]:22                     [::]:*                    
[root@localhost html]# curl 192.168.222.250  //访问
hello lnh

访问:

[root@localhost html]# cd
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 location / {
            root   html;
            index  index.html index.htm;
            allow 192.168.222.250;     //添加(只允许这个ip访问)
            deny all;                  //添加(拒绝其他ip访问)
        }
[root@localhost ~]# curl 127.0.0.1     //本机ip在虚拟机里面无法访问
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
[root@localhost ~]# curl 192.168.222.250  //允许的ip可以访问
hello lnh

使用本机ip在网页上面访问:

//此时也是无法访问的

nginx用户认证

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file" //密码存放位置

[root@localhost ~]# dnf -y install httpd-tools
//安装httpd工具包
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 location / {
            root   html;
            index  index.html index.htm;
            auth_basic "hello";      //添加
            auth_basic_user_file "/usr/local/nginx/conf/.pass"; //密码存放位置
        }
[root@localhost ~]# systemctl daemon-reload 
//重新加载一下配置
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# htpasswd -cm /usr/local/nginx/conf/.pass tushanbu
//生成用户密码
New password:                //新密码
Re-type new password:        //再次输入
Adding password for user tushanbu
[root@localhost conf]# cat .pass 
tushanbu:$apr1$kNKZPdty$rn3EvbmPAL0XYTSWPzSmt1
//加密后的密码
[root@localhost conf]# systemctl restart nginx.service 
//重启服务

使用谷歌浏览器进行访问:

https配置

生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中进行配置
证书申请及签署步骤:

  1. 生成申请请求
  2. RA核验
  3. CA签署
  4. 获取证书
[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)
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 req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN        //国家
State or Province Name (full name) []:HB    //省份
Locality Name (eg, city) [Default City]:WH  //城市
Organization Name (eg, company) [Default Company Ltd]:PX 组织
Organizational Unit Name (eg, section) []:www.example.com //部门
Common Name (eg, your name or your server's hostname) []:www.example.com    //域名
Email Address []:136@78.com    //邮箱
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# ls
cacert.pem  certs  crl  newcerts  private
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# 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]# 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]:PX
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:136@78.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365   
//签署证书
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 13 14:47:54 2022 GMT
            Not After : Oct 13 14:47:54 2023 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = PX
            organizationalUnitName    = www.example.com
            commonName                = www.example.com
            emailAddress              = 136@78.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                0E:2D:C4:CD:75:04:54:AF:D9:CD:0E:1E:1E:01:13:BE:DB:E8:39:EA
            X509v3 Authority Key Identifier: 
                keyid:84:C1:11:1D:9A:90:0D:AF:2C:EA:FD:10:40:D5:FF:C3:07:7F:FD:D0

Certificate is to be certified until Oct 13 14:47:54 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]# ls
nginx.crt  nginx.csr  nginx.key
[root@localhost ssl]# cd ..
[root@localhost conf]# vim nginx.conf //修改配置文件加入生成的密钥和证书
//先取消注释再修改
server {
        listen       443 ssl;
        server_name  www.example.com;

        ssl_certificate      /usr/local/nginx/conf/ssl/nginx.crt; //证书存放的位置
        ssl_certificate_key  /usr/local/nginx/conf/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;
        }
    }

}
[root@localhost conf]# systemctl restart nginx.service 
//重启服务

访问:


Nginx启用状态页面

开启status:stub_status [on | off]; (不添加参数默认on)
应用于server,location段
下载新模块地址
如果没有可以下载到本地,然后上传到nginx服务器
或者安装我前面平滑升级里面的方法来

[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 --add-module=../nginx_module_echo
//首先得有--with-http_stub_status_module模块
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf //编辑配置文件,开启状态页面
location = /status {
           stub_status;
        }
[root@localhost ~]# systemctl restart nginx.service 
//重启服务
[root@localhost ~]# curl 127.0.0.1/status  //查看访问结果
Active connections: 1 
server accepts handled requests
 1 1 1 
Reading: 0 Writing: 1 Waiting: 0 

访问:

状态页面信息详解:

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

zabbix监控Nginx状态

环境说明

主机名 ip 服务 系统
zabbix 192.168.222.250 lamp
zabbix-server
zabbix-agentd
centos8
nginx 192.168.222.137 nginx
zabbix_agentd
centos8

zabbix的安装部署以及一些操作可以看我的博客监控服务zabbix部署,zabbix的基础使用,
zabbix监控详解里面有zabbix部署和lamp的详细操作
nginx还是进行源码安装

nginx端,安装zabbix_agentd
zabbix-6.2源码包

[root@nginx ~]# cd /usr/local/etc/
[root@nginx etc]#  useradd -rMs /sbin/nologin zabbix //创建zabbix用户
[root@nginx etc]# cd /usr/src/
[root@nginx src]# wget https://cdn.zabbix.com/zabbix/sources/stable/6.2/zabbix-6.2.2.tar.gz  //下载源码包
[root@nginx src]# ls
debug  kernels  zabbix-6.2.2.tar.gz
[root@nginx src]# tar xf zabbix-6.2.2.tar.gz  //解压
[root@nginx src]# cd zabbix-6.2.2/
[root@nginx zabbix-6.2.2]# dnf -y install openssl-devel pcre-devel expat-devel gcc gcc-c++ make  //安装依赖包
[root@nginx zabbix-6.2.2]# ./configure --enable-agent
//进行编译
....
***********************************************************
*            Now run 'make install'                       *
*                                                         *
*            Thank you for using Zabbix!                  *
*              <http://www.zabbix.com>                    *
***********************************************************
[root@nginx zabbix-6.2.2]# make install  //安装
[root@nginx zabbix-6.2.2]# cd /usr/local/etc/
[root@nginx etc]# ls
zabbix_agentd.conf  zabbix_agentd.conf.d
[root@nginx etc]# vim zabbix_agentd.conf
//修改配置文件
Server=192.168.222.250   //服务端ip
ServerActive=192.168.222.250  //服务端ip
Hostname=Zabbix xbz  //zabbix系统内主机名,可自定义,但要确保唯一性
[root@nginx etc]# ldconfig    //刷新配置
[root@nginx etc]# zabbix_agentd   //启动zabbix_agentd
[root@nginx etc]# ss -antl      //查看端口
State      Recv-Q     Send-Q         Local Address:Port            Peer Address:Port     Process     
LISTEN     0          128                  0.0.0.0:22                   0.0.0.0:*                    
LISTEN     0          128                  0.0.0.0:10050                0.0.0.0:*                    
LISTEN     0          128                  0.0.0.0:80                   0.0.0.0:*                    
LISTEN     0          128                     [::]:22                      [::]:*                    

开启状态页面,并在nginx端写监控脚本

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

....
location = /status {
            stub_status;
            allow 127.0.0.1;  //只允许本地ip访问
            deny all;         //拒绝其他ip访问
       }
[root@nginx ~]# systemctl restart nginx.service 
//重启服务
[root@nginx ~]# mkdir /scripts
[root@nginx ~]# cd /scripts/
[root@nginx scripts]# vim nginx_status.sh
[root@nginx scripts]# cat nginx_status.sh
#/bin/bash

case $1 in
    Reading)
        curl -s 127.0.0.1/status |awk "NR==4{print\$2}"
        ;;
    Writing)
        curl -s 127.0.0.1/status |awk "NR==4{print\$4}"
        ;;
    Waiting)
        curl -s 127.0.0.1/status |awk "NR==4{print\$6}"
        ;;
        *)
            exit
            ;;
esac
[root@nginx scripts]# chmod +x nginx_status.sh 
[root@nginx scripts]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1     //取消注释并修改
UserParameter=nginx_status[*],/bin/bash /scripts/nginx_status.sh $1   //取消注释并修改
[root@nginx scripts]# pkill zabbix_agentd   //关闭
[root@nginx scripts]# zabbix_agentd         //开启
[root@nginx scripts]# ss -antl
State      Recv-Q     Send-Q         Local Address:Port            Peer Address:Port     Process     
LISTEN     0          128                  0.0.0.0:22                   0.0.0.0:*                    
LISTEN     0          128                  0.0.0.0:10050                0.0.0.0:*                    
LISTEN     0          128                  0.0.0.0:80                   0.0.0.0:*                    
LISTEN     0          128                     [::]:22                      [::]:*                    

在zabbix端进行测试

[root@zabbix ~]# zabbix_get -s 192.168.222.137 -k nginx_status[Writing]
1

创建监控主机



添加监控项






成功监控

查看监控值



rewrite

语法:rewrite regex replacement flag;

应用场景:
server字段
location字段
if字段

//如:
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 ~]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]# cd html/
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# mkdir tushanbu  //创建存放要编辑内容或者网站的目录
[root@localhost html]# cd tushanbu/
[root@localhost tushanbu]# ls
1.jpg             //可以在网上找一张喜欢的图片(格式为jpg)弄进来
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
...
  location / {
             root   html;
             index  index.html;
        }
...
[root@localhost html]# systemctl reload nginx.service 
//重新加载配置

访问:

如果我们将此目录做了修改,将tushanbu修改为imgs,那么用户使用原有的访问方式就访问不到了,而我们又不可能去告诉用户新的访问链接,所以,我们可以用rewrite去匹配用户输入的链接将其修改为新的链接,这样用户就相当于用旧的链接去访问到了新的连接,而用户并不知情确还是按照之前的访问方式进行正常访问

[root@localhost html]# mv tushanbu imgs
[root@localhost html]# ls 
50x.html  imgs  index.html
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
 location / {
             root   html;
             index  index.html;
        }
        location /tushanbu {               //添加
            rewrite ^/tushanbu/(.*)$ /imgs/$1 break;  //添加
        }                                  //添加
[root@localhost html]# systemctl reload nginx.service 
//重新加载配置

访问:

现在有一个nginx服务器,虚拟主机server_name为www.xbz.com,用户使用www.xbz.com/tushanbu/1.jpg可以访问到一个图片,但是现在将tushanbu这个目录进行了重命名,重命名后目录名为imgs,并且将这个目录单独拿出来做了一个虚拟主机,server_name为www.xbz2.com,但是用户并不知情,所以必须让用户使用原链接同样可以进行访问,访问到的内容还是之前的内容

先将原来的虚拟主机的网站进行改:

[root@localhost ~]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]# cd html/
[root@localhost html]# ls
50x.html  index.html  tushanbu
[root@localhost html]# ls tushanbu/     //图片存放的位置
1.jpg
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       80;
        server_name  www.xbz1.com;
...
 location /tushanbu {
            rewrite ^/tushanbu/.*\.jpg$ http://ww.xbz2.com/1.jpg break;
        }
...
[root@localhost html]# systemctl reload nginx.service 
//重新加载配置

再添加另外一个网站:

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
  server {
       listen       80;
       server_name  www.xbz2.com;
       location / {
           root html/tushanbu;     //图片存放的位置
           index index.html;
       }
 }
[root@localhost html]# systemctl reload nginx.service 
//重新加载配置

在物理机(自己电脑上面)的hosts文件里添加域名映射(C:\Windows\System32\drivers\etc)

原来的虚拟主机网站访问:

添加的另外一个网站进行正常的访问的访问:

我们输入的是原链接(www.xbz1.com/tushanbu/1.jpg),但是回车进行访问后,URL被重写成了www.xbz2.com/1.jpg

if

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

  1. server段
  2. location段

常见的condition

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

基于浏览器实现分离案例

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

相关内容

    暂无相关文章