菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
265
0

nginx

原创
05/13 14:22
阅读数 93030

nginx简介

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

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

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

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

nginx的特性与优点

nginx的特性

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

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

nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

nginx的功能及应用类别

nginx的基本功能

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

nginx的扩展功能

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

nginx的应用类别

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

nginx的模块与工作原理

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

nginx的模块分类

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

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

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

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

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

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

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

nginx的工作原理

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

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

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

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

image

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

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

nginx的配置文件详解

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

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

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

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

nginx.conf配置详解

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

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

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

通用配置

$remote_addr 与 $http_x_forwarded_for 用以记录客户端的ip地址;

$remote_user :用来记录客户端用户名称;

$time_local : 用来记录访问时间与时区;

$request : 用来记录请求的url与http协议;

$status : 用来记录请求状态;成功是200;

$body_bytes_s ent :记录发送给客户端文件主体内容大小;

$http_referer :用来记录从那个页面链接访问过来的;

$http_user_agent :记录客户端浏览器的相关信息;

每个指令必须有分号结束。

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

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 errorcrit alert emerg

正常运行必备的配置参数

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值

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

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 [...];后面可跟多个主机,名称可使用正则表达式或通配符

常需要进行调整的参数

  • worker_processes
  • worker_connections
  • worker_cpu_affinity
  • worker_priority

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时,匹配顺序如下:
 
先做精确匹配检查
左侧通配符匹配检查,如*.idfsoft.com
右侧通配符匹配检查,如mail.*
正则表达式匹配检查,如~ ^.*\.idfsoft\.com$
default_server

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

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

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

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

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

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

常用修饰符说明:

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

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

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

nginx平滑升级

过程:
1.获取之前的编译参数

2.下载新模块

3.重新编译软件,--add-module=新模块的路径

4.编译,替换主程序(原程序先备份)

5.启动新程序

[root@nginx ~]# wget https://github.com/openresty/echo-nginx-module/archive/refs/heads/master.zip
--2021-05-30 23:00:09--  https://github.com/openresty/echo-nginx-module/archive/refs/heads/master.zip
Resolving github.com (github.com)... 13.250.177.223
Connecting to github.com (github.com)|13.250.177.223|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://codeload.github.com/openresty/echo-nginx-module/zip/refs/heads/master [following]
--2021-05-30 23:00:10--  https://codeload.github.com/openresty/echo-nginx-module/zip/refs/heads/master
Resolving codeload.github.com (codeload.github.com)... 13.229.189.0
Connecting to codeload.github.com (codeload.github.com)|13.229.189.0|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/zip]
Saving to: ‘master.zip’

master.zip                       [ <=>                                         ]  75.35K   451KB/s    in 0.2s    

2021-05-30 23:00:11 (451 KB/s) - ‘master.zip’ saved [77163]


[root@nginx ~]#  unzip master.zip
[root@nginx ~]# nginx -V
nginx version: nginx/1.20.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC) 
built with OpenSSL 1.1.1g FIPS  21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

[root@nginx ~]# tar -xf nginx-1.20.0.tar.gz
 
[root@nginx nginx-1.20.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-master/
 
[root@nginx nginx-1.20.0]# make

//替换主程序
[root@nginx nginx-1.20.0]# mv /usr/local/nginx/sbin/nginx /opt/nginx_$(date +%F)
[root@nginx nginx-1.20.0]# mv objs/nginx /usr/local/nginx/sbin/
[root@nginx nginx-1.20.0]# kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
[root@nginx nginx-1.20.0]# nginx -V
nginx version: nginx/1.20.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1g FIPS  21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master/

Nginx信号简介

主进程支持的信号

  • TERM, INT: 立刻退出
  • QUIT: 等待工作进程结束后再退出
  • KILL: 强制终止进程
  • HUP: 重新加载配置文件,使用新的配置启动工作进程,并逐步关闭旧进程。
  • USR1: 重新打开日志文件
  • USR2: 启动新的主进程,实现热升级
  • WINCH: 逐步关闭工作进程

工作进程支持的信号

  • TERM, INT: 立刻退出
  • QUIT: 等待请求处理结束后再退出
  • USR1: 重新打开日志文件

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

server {
        listen       80;
        server_name  localhost;
        location /test {
           echo "yc";
        }

有几种正确匹配的方式例如:

http://(IP地址)/test
http://(IP地址)/test?p1=11?p2=22
http://(IP地址)/test/

[root@yc ~]# curl 192.168.23.148/test
yc

[root@yc ~]# curl 192.168.23.148/test?p1=11?p2=22
yc

[root@yc ~]# curl 192.168.23.148/test/
yc

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

server {
        listen       80;
        server_name  localhost;
location = /test {
            echo "111";
        }

那么久可以使用这种匹配方式例如:

http://ip/test
http://ip/test?p1=qq?p2=ww
[root@yc ~]# curl 192.168.23.148/test
111

[root@yc ~]# curl 192.168.23.148/test?p1=qq?p2=22
111

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

server {
    listen       80;
    server_name  localhost;
location ~ /test$ {
            echo "222";
        }

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

http://ip/test
http://ip/test?p1=qq?p2=ww
[root@yc ~]# curl 192.168.23.148/test
222

[root@yc ~]# curl 192.168.23.148/test?p1=11?p2=22
222

如下内容则无法匹配:

http://ip/test/
http://ip/TEST
http://ip/testabc
[root@yc ~]# curl 192.168.23.148/test/
<htm1 >
<head><tit1e>404 Not FoundK/ ti t1e></head>
<body>
<center><h1>404 Not F ound</h1></center>
<hr><center>nginx/ 1. 20. 0</ center>
<body>
<htm1>

[root@yc ~]# curl 192.168.23.148/TEST/
<htm1 >
<head><tit1e>404 Not FoundK/ ti t1e></head>
<body>
<center><h1>404 Not F ound</h1></center>
<hr><center>nginx/ 1. 20. 0</ center>
<body>
<htm1>

[root@yc ~]# curl 192.168.23.148/test222/
<htm1 >
<head><tit1e>404 Not FoundK/ ti t1e></head>
<body>
<center><h1>404 Not F ound</h1></center>
<hr><center>nginx/ 1. 20. 0</ center>
<body>
<htm1>

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

server {
    listen       80;
    server_name  localhost;
    location ~* /test$ {
       echo "333";
    }

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

http://ip/test
http://ip/test?p1=qq?p2=ww
http://ip/TEST
[root@yc ~]# curl 192.168.23.148/test
333

[root@yc ~]# curl 192.168.23.148/test?p1=qq?p2=ww
333

[root@yc ~]# curl 192.168.23.148/TEST
333

如下内容则无法匹配:

http://ip/test/
http://ip/testabc
[root@yc ~]# curl 192.168.23.148/test/
<htm1 >
<head><tit1e>404 Not FoundK/ ti t1e></head>
<body>
<center><h1>404 Not F ound</h1></center>
<hr><center>nginx/ 1. 20. 0</ center>
<body>
<htm1>

[root@yc ~]# curl 192.168.23.148/test333/
<htm1 >
<head><tit1e>404 Not FoundK/ ti t1e></head>
<body>
<center><h1>404 Not F ound</h1></center>
<hr><center>nginx/ 1. 20. 0</ center>
<body>
<htm1>

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

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

优先级次序如下:

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

访问控制

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

//拒绝所有,这样的话所有的连接都不能访问到test下面的内容
location  /1.html {
            deny all;
         #   allow ;
        }

image

//单独禁用一些地址,例如我禁用我自己物理机的IP
location  /1.html {
            deny 192.168.1.11;
            deny 192.168.1.112;
            allow all;
//但是我的虚拟机可以访问
[root@nginx ~]# curl http://192.168.1.112/test/index.html
yc
[root@nginx ~]# curl http://192.168.1.112/test/index.html
yc

如果你把参数写到server里面,他是针对整个网站的

//我只放行了虚拟机IP访问nginx,拒绝了所有其他机器
server {
        listen       80;
        server_name  localhost;
        allow 192.168.1.112;
        deny all;
//虚拟机可以访问
[root@nginx ~]# curl 192.168.1.112
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;

本地机访问页面403
image

  • 得出结论,如果配置在location字段里面是针对某个资源,配置在server里是针对整个网站

基于用户认证

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

//user_auth_file内容格式为:
[root@nginx ~]# cat user_auth_file
username:password

//这里的密码为加密后的密码串,建议用htpasswd来创建此文件:
[root@nginx ~]# yum -y install httpd-tools
[root@nginx ~]# htpasswd -c -m /path/to/.user_auth_file USERNAME
New password:
Re-type new password:
Adding password for user xiaoming
 
[root@nginx ~]# vim /etc/nginx/nginx.conf
..........................
        location / {
          auth_basic  "hello";
          auth_basic_user_file "/etc/nginx/.auth_user";
        }

访问测试
image

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;
  }
}
#创建证书和私钥的目录
[root@nginx ~]# cd /etc/nginx/
[root@nginx ~]# mkdir CA
 
#创建服务器私钥,命令会让你输入一个口令
#注意,centos版本如果是CentOS Linux release 8.0.1905 (Core)版本,私钥长度不能设置成1024位,必须2048位
[root@nginx ~]# cd CA
[root@nginx CA]# openssl genrsa -des3 -out server.key 2048
 
#创建签名请求的证书(CSR),设置信息
[root@nginx CA]# openssl req -new -key server.key -out server.csr
 
 
#标记证书使用上述私钥和CSR
[root@nginx CA]# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
 
#配置nginx
[root@nginx CA]# vim /etc/nginx/nginx.conf
 server {
        listen       443 ssl ;
        server_name  www.xxxx.com;
        root         /usr/share/nginx/html;
 
        ssl_certificate "/etc/nginx/CA/server.crt";
        ssl_certificate_key "/etc/nginx/CA/server.key";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers PROFILE=SYSTEM;
        ssl_prefer_server_ciphers on;
 
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
 
        location / {
        }
 
        error_page 404 /404.html;
            location = /40x.html {
        }
 
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

使用zabbix监控nginx状态

在nginx客户端安装zabbix客户端

//关闭防火墙与seliunx
[root@nginx ]# systemctl stop firewalld
[root@nginx ]# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@nginx ]# setenforce 0
[root@nginx ]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@nginx ~]# wget https://cdn.zabbix.com/zabbix/sources/stable/5.2/zabbix-5.2.6.tar.gz
[root@nginx ~]# tar xf zabbix-5.2.6.tar.gz 
[root@nginx ~]# cd zabbix-5.2.6/
[root@nginx zabbix-5.2.6]# ./configure --enable-agent
[root@nginx zabbix-5.2.6]# make install
[root@nginx ~]# useradd -r -M -s /sbin/nologin zabbix

//修改配置文件
[root@nginx ~]# vim /usr/local/etc/zabbix_agentd.conf
······
Server=192.168.23.148			#修改成服务端IP
······
ServerActive=192.168.23.148		#修改成服务端IP
······
Hostname=nginx

[root@nginx ~]# zabbix_agentd      
[root@nginx ~]# ss -antl
State     Recv-Q    Send-Q         Local Address:Port          Peer Address:Port    
LISTEN    0         128                  0.0.0.0:10050              0.0.0.0:*          LISTEN    0         128                  0.0.0.0:22                 0.0.0.0:*         
LISTEN    0         128                     [::]:22                    [::]:*	

编写脚本

[root@nginx ~]# mkdir /usr/local/etc/zabbix_scripts -p
[root@nginx ~]# vim /usr/local/etc/zabbix_scripts/nginx_status.sh
#!/bin/bash
case $1 in
    Active)
    /usr/bin/curl -s 127.0.0.1/status | awk 'NR==1 {print $3}'
    ;;
        reading)
    /usr/bin/curl -s 127.0.0.1/status | grep 'Reading'|cut -d" " -f2
    ;;
    Writing)
    /usr/bin/curl -s 127.0.0.1/status | grep 'Writing'|cut -d" " -f4
        ;;
    Waiting)
        /usr/bin/curl -s 127.0.0.1/status | grep 'Waiting'|cut -d" " -f6
        ;;
        acceptes)
    /usr/bin/curl -s 127.0.0.1/status | awk 'NR==3{print $1}'
    ;;
    handled)
    /usr/bin/curl -s 127.0.0.1/status | awk 'NR==3{print $2}'
    ;;
    requests)
    /usr/bin/curl -s 127.0.0.1/status | awk 'NR==3{print $3}'
        ;;
    *)
        echo "Usage: $0 {Active|reading|Writing|Waiting|acceptes|handled|requests}"
    ;;
esac

////添加执行权限
[root@nginx ~]# chmod /usr/local/etc/zabbix_scripts/nginx_status.sh

//添加键值
[root@nginx zabbix-5.2.6]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1
UserParameter=nginx_check_status[*],/usr/local/etc/zabbix_scripts/nginx_status.sh $1

//重启zabbix
[root@nginx ~]# pkill zabbix
[root@nginx ~]# zabbix_agentd

测试zabbix获取值

[root@nginx ~]#zabbix_get  -s 192.168.23.148 -k  'nginx_check_status[Active]'
1
[root@nginx ~]#zabbix_get  -s 192.168.23.148 -k  'nginx_check_status[Writing]'
1

image
image

发表评论

0/200
265 点赞
0 评论
收藏