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

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

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

在这里插入图片描述

​ 上图简述:首先用户通过http或https的协议去请求访问资源在中间这台主机,然后maser进程就去找到某一个worker线程去处理,如果要访问的资源在本地就直接在本地的硬盘或缓存中去拿,如果不在本地就交给后端的服务器,通过FastCGI协议找到需要的资源或memcache缓存协议去找缓存,然后再返回。

下面是nginx模块每一次常规的http请求和响应的过程

在这里插入图片描述

​ 上图简述: 用户发出请求,nginx内核收到请求后,选择一个处理器模块去处理,生成一个内容,去过滤多次处理,然后响应请求。

下面是基本的Web 服务请求步骤

在这里插入图片描述

​ 上图简述:首先客户端与服务端建立连接,通过TCP/IP进行三次握手建立连接,(因为是tcp传输层协议,每一个协议对应一个端口号,所以就找到了80端口号)连接到80端口上,然后接收请求,解封装后发现要请求的是资源,然后就去处理,通过mater进程去选择一个worker线程去处理,处理之后去访问资源,在服务端的硬盘中或另一台主机上面,取到资源,返回给服务的主进程,然后构建响应报文(用户需要的东西已经拿到),通过网络接口发送响应报文发给客户端,用户就拿到需要的数据了,然后记录整个操作过程到日志中。

nginx的安装

安装依赖包和工具包

[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make wget
[root@localhost ~]# yum -y group mark install "Development Tools"

创建用户

[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx

创建日志存放目录

[root@localhost ~]# mkdir /var/log/nginx -p

下载nginx,解压(nginx官网

[root@localhost ~]# cd /usr/src/soft/
[root@localhost soft]# wget http://nginx.org/download/nginx-1.20.1.tar.gz
[root@localhost soft]# ls
nginx-1.20.1.tar.gz

[root@localhost soft]# tar xf nginx-1.20.1.tar.gz -C /usr/local
[root@localhost soft]# cd /usr/local/
[root@localhost local]# ls
bin  games    lib    libexec   sbin   src
etc  include  lib64  mysql    nginx-1.20.1                         share

编译安装

# 当然在编译之前我们可以看一下选项
[root@localhost logs]# cd /usr/local/nginx-1.20.1/
[root@localhost nginx-1.20.1]# ./configure --help

  --help                             print this message
  .......
  --with-select_module               enable select module  # --with-...就是和什么在一起,需要的,说明默认是没有的
  --without-select_module            disable select module 
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module # # --without-...就是不需要的,可以关闭,说明默认是有的
  ..........

[root@localhost nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
.......
checking for OS
 + Linux 4.18.0-257.el8.x86_64 x86_64
checking for C compiler ... found
......
nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"
  
  [root@localhost nginx-1.20.1]# make && make install
安装后配置
配置环境变量
[root@localhost local]# nginx
-bash: nginx: command not found
[root@localhost local]# echo "export PATH=/usr/local/nginx/sbin:$PATH" > /etc/profile.d/nginx.sh
[root@localhost local]# bash
[root@localhost local]# which nginx
/usr/local/nginx/sbin/nginx

# 服务控制方式,使用nginx命令
#    -t  //检查配置文件语法
#    -v  //输出nginx的版本
#    -c  //指定配置文件的路径
#    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}
启动nginx
[root@localhost ~]# /usr/local/nginx/sbin/nginx
[root@localhost ~]# ss -antl
State    Recv-Q    Send-Q       Local Address:Port       Peer Address:Port   Process   
LISTEN   0         128                0.0.0.0:22              0.0.0.0:*                
LISTEN   0         128                0.0.0.0:80(nginx端口)              0.0.0.0:*                
LISTEN   0         128                   [::]:22                 [::]:*
给nginx配置开机自启
[root@localhost ~]# cp /usr/lib/systemd/system/sshd.service /usr/lib/systemd/system/nginxd.service
[root@localhost ~]# vim /usr/lib/systemd/system/nginxd.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
KillMode=process

[Install]
WantedBy=multi-user.target

[root@localhost ~]# systemctl daemon-reload          # 重新加载
[root@localhost ~]# systemctl enable --now nginxd    # 启动nginx并设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/nginxd.service → /usr/lib/systemd/system/nginxd.service.

配置文件详解

主配置文件:安装路径下的/nginx/conf/nginx.conf

  • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件

  • 可以在启动nginx时通过-c选项来指定要读取的配置文件

    比如我们可以指定复制一份指定的nginx文件来配置启动nginx,

[root@localhost ~]# cd /usr/local/nginx
[root@localhost nginx]# ls
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp

# conf   主配置文件
# logs   日志文件
# sbin   主程序文件
# 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]# vim nginx.conf  # 默认的配置
  1 
  2 #user  nobody;
  3 worker_processes  1;              # nginx work线程默认的只有一个
  4 
  5 #error_log  logs/error.log;
  6 #error_log  logs/error.log  notice;
  7 #error_log  logs/error.log  info;
  ........
  
[root@localhost opt]# ps -aux |grep nginx
root       77079  0.0  0.0  81632  1088 ?        Ss   03:24   0:00 nginx: master process nginx
nginx      77080  0.0  0.3 114304  5832 ?        S    03:24   0:00 nginx: worker process(一个)
root      136092  0.0  0.0   9208  1080 pts/0    S+   03:39   0:00 grep --color=auto nginx

[root@localhost conf]# cp nginx.conf /opt/   # 复制一份到/opt/目录进行修改,然后使用/opt/下的nginx.conf文件来启动
[root@localhost conf]# cp mime.types /opt/
[root@localhost conf]# cd /opt/
[root@localhost opt]# ls
data  nginx.conf mime.types
[root@localhost opt]# vim nginx.conf
  1 
  2 #user  nobody;
  3 worker_processes  3;           # 修改默认的配置worker线程为3个,然后使用-c启动指定要读取的配置文件/opt/nginx.conf
  4 
  5 #error_log  logs/error.log;
  6 #error_log  logs/error.log  notice;
  7 #error_log  logs/error.log  info;
  ......
  
[root@localhost opt]# nginx -t  # 使用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 opt]# nginx -s stop;nginx -c /opt/nginx.conf # 停掉nginx,然后立马使用指定的配置文件启动,如果指定路径下的配置文件有问题,直接使用"nginx"命令启动默认的进程

[root@localhost opt]# ps -aux |grep nginx   # 查看进程发现使用指定的文件启动了三个worker线程
root      161859  0.0  0.0  81632  1092 ?        Ss   03:46   0:00 nginx: master process nginx -c /opt/nginx.conf
nginx     161860  0.0  0.3 114304  6192 ?        S    03:46   0:00 nginx: worker process(一)
nginx     161861  0.0  0.3 114304  6216 ?        S    03:46   0:00 nginx: worker process(二)
nginx     161862  0.0  0.3 114304  6184 ?        S    03:46   0:00 nginx: worker process(三)
root      162394  0.0  0.0   9208  1152 pts/0    S+   03:46   0:00 grep --color=auto nginx
当然默认的nginx端口号也是可以修改的
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# ls
fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          scgi_params  uwsgi_params          win-utf   fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params.default  uwsgi_params.default

[root@localhost conf]# vim nginx.conf
......
 35     server {
 36         listen       4444;    # 默认端口号是80,我们可以对其进行修改,这里我改成了4444
 37         server_name  localhost;
 38 
 39         #charset koi8-r;
 40 
 41         #access_log  logs/host.access.log  main;
 .....
 
[root@localhost conf]# nginx -s reload   # 重新加载后查看端口
[root@localhost conf]# 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:4444(已发生改变)                           0.0.0.0:*                                
LISTEN           0                128                                   [::]:22                                 [::]:*

访问测试

在这里插入图片描述

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

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

nginx.conf配置详解

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

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

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

derective value1 [value2 ...];

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value
用于调试、定位问题的配置参数

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

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

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

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
比如修改默认配置文件让守护进程直接到前台运行,而不是在后台运行

[root@localhost ~]# cd /usr/local/nginx
[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]# vim nginx.conf
[root@localhost conf]#
  1 
  2 #user  nobody;
  3 worker_processes  1;
  4 
  5 daemon off;       # 添加此行,将nginx的后台运行关闭,就变成了前台运行
  6 
  7 #error_log  logs/error.log;
  8 #error_log  logs/error.log  notice;
  9 #error_log  logs/error.log  info;
......

[root@localhost ~]# /usr/local/nginx/sbin/nginx -s stop  # 停止nginx
[root@localhost ~]# /usr/local/nginx/sbin/nginx         # 启动,启动后发现卡住不动了,说明nginx已经变成前台运行

访问网页也是正常的
在这里插入图片描述

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

位置级别
file stderr syslog:server=address[,parameter=value] memory:size若要使用debug级别,需要在编译nginx时使用–with-debug选项 debug 调试 info 信息 notice 请注意 warn 警告 error 错误 crit 暴击 alert 警报 emerg 紧急情况

比如将配置文件中的记录日志的注释取消掉,然后可以修改日志级别,就有记录了,日志级别越低,越详细,但是无用的记录也越多,所以我们应该选择适当的日志级别,比如我们设置的是crit级别,但是看不出来什么错误,我们就可以降低级别来查看更详细的记录

[root@localhost ~]# cd /usr/local/nginx/logs/
[root@localhost logs]# ls
nginx.pid             # 现在是没有日志文件的(除了pid)

[root@localhost logs]# cd ../conf/
[root@localhost nginx]# vim conf/nginx.conf
  1 
  2 #user  nobody;
  3 worker_processes  1;
  4 
  5 error_log  logs/error.log;                   # 取消注释
  6 #error_log  logs/error.log  notice;
  7 #error_log  logs/error.log  info;
  8 
  9 #pid        logs/nginx.pid;

[root@localhost conf]# nginx -s reload      # 重新加载
[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]# cd ../logs/
[root@localhost logs]# ls
error.log  nginx.pid                        # 出现一个错误日志

[root@localhost nginx]# ll logs/
total 4
-rw-r--r--. 1 root root 0(空的) Oct 25 04:35 error.log
-rw-r--r--. 1 root root 7 Oct 25 04:27 nginx.pid

在nginx页面基础上访问下不存在的页面

在这里插入图片描述

[root@localhost nginx]# ll logs/
total 8
-rw-r--r--. 1 root root 223(有记录了) Oct 25 04:39 error.log
-rw-r--r--. 1 root root   7 Oct 25 04:27 nginx.pid

# 查看error.log日志,里面的记录就是上面访问页面的错误信息
[root@localhost nginx]# cat logs/error.log
2021/10/25 04:39:24 [error] 342492#0: *3 open() "/usr/local/nginx/html/gdfjgkdjgd" failed (2: No such file or directory), client: 192.168.220.1, server: localhost, request: "GET /gdfjgkdjgd HTTP/1.1", host: "192.168.220.9"
正常运行必备的配置参数

使用的时候直接在配置文件中指明使用的用户是nginx

user USERNAME [GROUPNAME];    # 指定运行worker进程的用户和组

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
  1 
  2 user  nginx nginx;  # 取消注释,然后修改为nginx用户,nginx组
  3 worker_processes  1;
  .......
  [root@localhost conf]# nginx -s reload         # 发送信号重新加载配置文件立即生效

pid文件位置也取消注释直接使用,因为默认注释掉也是使用的这个位置,当然也可以修改为其他位置

pid /path/to/pid_file;    # 指定nginx守护进程的pid文件
........
  7 #error_log  logs/error.log  info;
  8 
  9 pid        logs/nginx.pid;   # 取消注释
  ..........
[root@localhost conf]# nginx -s reload         # 发送信号重新加载配置文件立即生效

设置worker线程最大可以打开的文件数

worker_rlimit_nofile number;    # 更改worker线程中最大开放文件数量的限制。用于在不重新启动主过程的情况下增加限制。默认为1024,但是1024太小了,所以我们可以设置为10240

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
  1 
  2 user  nginx nginx;
  3 worker_processes  1;
  4 worker_rlimit_nofile 10240;   # 添加此行,并设置为10240,默认是1024
  ...........
  [root@localhost conf]# nginx -s reload         # 发送信号重新加载配置文件立即生效

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

worker_rlimit_core size; 
性能优化的配置参数

启动worker线程个数,把进程进行切换就是上下文切换,(寄存器)记录运行的位置,上下文切换的信息会一直被保存在CPU的内存中,直到被再次使用。

worker_processes n;

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
  1 
  2 user  nginx nginx;
  3 worker_processes  3;      # 默认是1,更改就可以产生多个worker线程去处理
  4 worker_rlimit_nofile 10240;
  [root@localhost conf]# nginx -s reload         # 发送信号重新加载配置文件立即生效

将进程绑定到某cpu核心中,避免频繁刷新缓存。绑定规则是核心数-1,比如总核心数为4,那么就绑定三个,另一个给其他使用

worker_cpu_affinity cpumask ...;
# 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核心

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
  1 
  2 user  nginx nginx;
  3 worker_processes  3;
  4 worker_rlimit_nofile 10240;
  5 worker_cpu_affinity 0001 0010 0100;  # 添加此行,为前面增加的三个worker线程绑定三个核心
  ....................
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s stop;nginx  # 重启nginx
# 查看是否生效: top命令,大写L搜索nginx,然后按小写f,移动到大写P,然后空格选中,最后按q退出就可以看见是否生效

可以看见最后面的大写P的下面的nginx核心数都不一样,这样就完成了绑定,提高了处理的速度
在这里插入图片描述
计时器解析度。降低此值,可减少gettimeofday()系统调用的次数。减少worker线程中的定时器分辨率,从而减少系统呼叫的数量。默认情况下,每次收到内核事件时都会被调用。随着分辨率的降低,每个指定呼叫一次。

timer_resolution interval;    
# 例如可以设置为   timer_resolution 100ms;

指明worker进程的nice值,优先级是-20到19,指定的数字越小,优先级越高,相对优先级(可以调整) ,绝对优先级,100到139(无法调整) ,提高优先级可以先进行处理

worker_priority number;   

[root@localhost ~]# ps -elf|grep nginx     # 查看发现worker线程的nice值是80,我们可以修改提高它的优先级,这样就可以优先进行处理
1 S root       34284       1  0  80   0 - 20408 -      01:35 ?        00:00:00 nginx: master process nginx
5 S nginx      34285   34284  0  80   0 - 28560 do_epo 01:35 ?        00:00:00 nginx: worker process
5 S nginx      34286   34284  0  80   0 - 28560 do_epo 01:35 ?        00:00:00 nginx: worker process
5 S nginx      34287   34284  0  80   0 - 28560 do_epo 01:35 ?        00:00:00 nginx: worker process
0 S root       99205   33695  0  80   0 -  2302 -      01:53 pts/0    00:00:00 grep --color=auto nginx

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
 1 
  2 user  nginx nginx;
  3 worker_processes  3;
  4 worker_rlimit_nofile 10240;
  5 worker_cpu_affinity 0001 0010 0100;
  6 worker_priority -20              # 添加此行来提高worker线程的优先级
  
[root@localhost conf]# nginx -s reload         # 发送信号重新加载配置文件立即生效
[root@localhost conf]# ps -elf|grep nginx     # 查看发现worker线程的nice值提高为60
1 S root       34284       1  0  80   0 - 20441 -      01:35 ?        00:00:00 nginx: master process nginx
5 S nginx     112949   34284  0  60 -20 - 28597 do_epo 01:56 ?        00:00:00 nginx: worker process
5 S nginx     112950   34284  0  60 -20 - 28597 do_epo 01:56 ?        00:00:00 nginx: worker process
5 S nginx     112951   34284  0  60 -20 - 28597 do_epo 01:56 ?        00:00:00 nginx: worker process
0 S root      113823   33695  0  80   0 -  2302 -      01:56 pts/0    00:00:00 grep --color=auto nginx
事件相关的配置:event{}段中的参数配置

accept_mutex {off|on}; 互斥锁,互相排斥,mster调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求 ,保持默认关闭的。

accept_mutex {off|on};
lock_file logs/nginx.lock;      # accept_mutex用到的互斥锁锁文件路径(main段)

指明使用的事件模型,建议让nginx自行选择。指定要使用的连接处理。通常不需要明确说明,因为 nginx 默认情况下会使用最有效的方法

use [epoll | rtsig | select | poll];    

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

worker_connections 1024;  

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
.......
 14 
 15 events {
 16     worker_connections  20480;  # 默认值是1024
 17 }
 ........
 
 # worker_connections 20480; 并发连接数 = 20480 * worker线程数量(3个)/2 
 # 使用ab命令测试并发,安装工具 **yum -y install httpd-tools**

 [root@localhost conf]# ab -n 30000(三万并发测试) http://192.168.220.9/(本机IP)    # 测试
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.220.9 (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


Server Software:        nginx/1.20.1
Server Hostname:        192.168.220.9
Server Port:            80

Document Path:          /
Document Length:        612 bytes

Concurrency Level:      1
Time taken for tests:   3.518 seconds
Complete requests:      30000
Failed requests:        0
Total transferred:      25350000 bytes
HTML transferred:       18360000 bytes
Requests per second:    8528.53 [#/sec] (mean)
Time per request:       0.117 [ms] (mean)
Time per request:       0.117 [ms] (mean, across all concurrent requests)
Transfer rate:          7037.70 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:     0    0   0.0      0       2
Waiting:        0    0   0.0      0       1
Total:          0    0   0.0      0       2

Percentage of the requests served within a certain time (ms)
  50%      0
  66%      0
  75%      0
  80%      0
  90%      0
  95%      0
  98%      0
  99%      0
 100%      2 (longest request)
网络连接相关的配置参数

长连接的超时时长,默认为65s

[root@localhost]# cd /usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
........
 32 
 33     #keepalive_timeout  0;
 34     keepalive_timeout  65;     # 默认值
 35 
 36     #gzip  on;
.......

设置可以通过一个保持活力连接服务的最大请求数量。请求的最大数目后,连接将关闭。
定期关闭连接是每个连接内存分配的必要条件。因此,使用过高的最大请求量可能导致内存使用过量,不推荐

keepalive_requests number;   # 可以添加在http段,server段,location段

[root@localhost]# cd /usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
........
 38     server {
 39         listen       80;
 40         server_name  localhost;
 41         keepalived_requests 10000   # 可以添加在server段
 42 
 43         #charset koi8-r;
.......

为指定类型的UserAgent(用户代理)禁用长连接

eepalive_disable [msie6(关闭Microsoft浏览器IE6的长连接)|safari(类mac的系统)|none(全部)];  

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

cp_nodelay on|off;   

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;
}
常需要进行调整的参数
  • worker_processes # worker线程数量
  • worker_connections # 并发连接数
  • worker_cpu_affinity # cpu核心数绑定
  • worker_priority # worker线程的优先级
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 81;(端口)
​     server_name www.lp.com;(域名可以给多个)
​      location / {
​      root html/test;  (网站位置)  or  alias /var/www/html/;(别名,但是别名一定要写绝对路径,就是把资源放到另外一个位置,当有人访问时,看见的路径是/根下面,其实我们已经放在了另一个位置,防止被攻击)
​      index    index.html;

​    }

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

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
.......
 51         error_page  404  /404.html;         # 404 错误页面
 52 
 53         # redirect server error pages to the static page /50x.html
 54         #
........

当我们去访问一个不存在的页面,会报错404
在这里插入图片描述

那么我们访问的页面出现404错误的时候,我们可以配置404的页面

[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html  index.html  index.php        # 没有404文件,创建一个,写入内容
[root@localhost html]# vi 404.html

<html>
<head>
    <title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>

当我们访问一个不存在的地方的时候出现404错误,就会跳到我们配置的404界面
在这里插入图片描述
在这里插入图片描述

log_format定义日志格式

访问日志,当我们去访问网站的时候就会把访问记录记录到access.log日志中

//取消日志的注释开始使用
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
........
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
access_log  logs/access.log  main;
.......
[root@localhost nginx]# nginx -s reload
[root@localhost nginx]# ll logs/access.log 
-rw-r--r-- 1 root root 0 Oct 27 01:39 logs/access.log

//注意:此处可用变量为nginx各模块内建变量,定义了日志的格式。

测试访问,查看日志内容
在这里插入图片描述

[root@localhost nginx]# cat logs/access.log 
192.168.220.1 - - [27/Oct/2021:01:42:49 -0400] "GET / HTTP/1.1"     
 304 0 "-" 
 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" "-"
 
//远程主机是192.168.220.1,远程用户是 -(无) ,本地时间是[27/Oct/2021:01:42:49 -0400],使用的是GET请求方法(向服务器请求资源),使用的是HTTP/1.1的版本
//响应状态码为304,发送的字节0,网站内容是怎么访问到的"-"
//用户的代理是(浏览器),从哪里跳转过来的"-"
平滑升级(添加功能,大概步骤)
  • 获取现有的程序编译的参数 nginx -V
  • 获取新版本的软件包或功能包
  • 将新功能或新版本进行编译
  • 备份原程序
  • 替换原程序

查看现有的程序编译的参数,后面编译新功能时要加上现有的参数编译

[root@localhost ~]# cd /usr/local/nginx-1.20.1/
[root@localhost nginx-1.20.1]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (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

删除nginx原来的主目录,重新解压一个

[root@localhost ~]# rm -rf /usr/local/nginx-1.20.1
[root@localhost ~]# tar xf /usr/src/soft/
[root@localhost ~]# tar xf /usr/src/soft/nginx-1.20.1.tar.gz -C /usr/local/

在GitHub上搜索echo nginx这个功能,下载并更新到nginx中
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

下载后上传
在这里插入图片描述

在这里插入图片描述

[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module-master.zip

//下载解压工具解压包
[root@localhost ~]# yum -y install unzip
[root@localhost ~]# unzip echo-nginx-module-master.zip
Archive:  echo-nginx-module-master.zip
32f52b61382ba223b9ab5df97c823395e6a2fbc5
......
inflating: echo-nginx-module-master/util/wiki2pod.pl  
inflating: echo-nginx-module-master/valgrind.suppress  
[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module-master  echo-nginx-module-master.zip

//使用./configure --help找到添加模块的命令,添加新模块包的路径然后回车进行配置
[root@localhost nginx-1.20.1]# ./configure --prefix=/usr/local/nginx \
--user=nginx --group=nginx --with-debug --with-http_ssl_module \
--with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module \
--with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log --add-module=/root/echo-nginx-module-master  # 在最后添加新的模块路径,使用--add-module命令
checking for OS
 + Linux 4.18.0-257.el8.x86_64 x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC)
......
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"
  
  # 查看nginx主目录中的objs下有无nginx程序,编译前应该是没有的
[root@localhost nginx-1.20.1]# ls
CHANGES  CHANGES.ru  LICENSE  Makefile  README  auto  conf  configure  contrib  html  man  objs  src
[root@localhost nginx-1.20.1]# ls objs/
Makefile  addon  autoconf.err  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  src  # 无nginx主程序

[root@localhost nginx-1.20.1]# make              # 编译
[root@localhost nginx-1.20.1]# ls objs/
Makefile  addon  autoconf.err  nginx(有了)  nginx.8  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  ngx_modules.o  src

# 对比新旧nginx程序大小,新的nginx程序应该要大一些
[root@localhost nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 6308640 Oct 26 00:49 /usr/local/nginx/sbin/nginx
-rwxr-xr-x  1 root root 6831128 Oct 27 02:49 objs/nginx   

# 备份旧的nginx主程序
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /opt
[root@localhost nginx-1.20.1]# ls /opt/
data  nginx

# 停掉旧的程序,指定旧的配置文件来启动新的程序
[root@localhost nginx-1.20.1]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf

[root@localhost nginx-1.20.1]# ss -antl        # 查看端口是否正常
State            Recv-Q           Send-Q                       Local Address:Port                       Peer Address:Port           Process           
LISTEN           0                128                              127.0.0.1:9000                            0.0.0.0:*                                
LISTEN           0                128                                0.0.0.0:80                              0.0.0.0:*                                
LISTEN           0                128                                0.0.0.0:22                              0.0.0.0:*                                
LISTEN           0                80                                       *:3306                                  *:*                                
LISTEN           0                128                                   [::]:22                                 [::]:*                                

# 查看是否成功
[root@localhost nginx-1.20.1]# ps -aux |grep nginx
root      535241  0.0  0.0  81660  1136 ?        Ss   02:59   0:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf # 成功
nginx     535242  0.0  0.5 118128  9956 ?        S<   02:59   0:00 nginx: worker process
nginx     535243  0.0  0.5 118128  9956 ?        S<   02:59   0:00 nginx: worker process
nginx     535244  0.0  0.5 118128 10016 ?        S<   02:59   0:00 nginx: worker process
root      543008  0.0  0.0   9208  1156 pts/0    S+   03:01   0:00 grep --color=auto nginx

# 测试新加的echo模块是否可用
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
 46         location / {
 47             root   html;
 48             index  index.html index.htm;
 49         }
 50         location  /test {        # 添加,当我要访问test时,就匹配到test然后打印输出test
 51             echo "test";         # 添加
 52         }                       # 添加
 .......
[root@localhost html]# /usr/local/nginx-1.20.1/objs/nginx -t   # 使用新的程序(/usr/local/nginx-1.20.1/objs/nginx)检查语法
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 ~]# /usr/local/nginx-1.20.1/objs/nginx -s reload

访问测试,只能通过命令行访问

[root@localhost ~]# curl 192.168.220.9/test
tset              # 测试没有问题

覆盖旧的nginx程序

[root@localhost ~]# cp /usr/local/nginx-1.20.1/objs/nginx /usr/local/nginx/sbin/nginx
cp: overwrite '/usr/local/nginx/sbin/nginx'? y

[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 ~]# /usr/local/nginx-1.20.1/objs/nginx -s stop;nginx        # 停止新的nginx程序,使用默认的

查看进程

[root@localhost ~]# ps -aux |grep nginx
root      652270  0.0  0.0  81660  1140 ?        Ss   03:30   0:00 nginx: master process nginx   # 已经变成默认的
nginx     652271  0.0  0.5 118128  9832 ?        S<   03:30   0:00 nginx: worker process
nginx     652272  0.0  0.5 118128  9976 ?        S<   03:30   0:00 nginx: worker process
nginx     652273  0.0  0.5 118128  9864 ?        S<   03:30   0:00 nginx: worker process
root      659160  0.0  0.0   9208  1148 pts/2    S+   03:32   0:00 grep --color=auto nginx

location区段

location是入口,千万不能配错;可以在http段配置(影响全局),server段(影响一个网站),location段(影响一个资源)

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

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

常用修饰符说明:

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

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

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

在配置文件中定义各个修饰符等级来访问

[root@localhost]# vim /usr/local/nginx/conf/nginx.conf
......
 46         location = /test {
 47             echo "TEST";
 48         }
 49 
 50         location / {
 51             root   html;
 52             index  index.html index.htm;
 53         }
 54 
 55         location ~ ^/abc {
 56             echo "tset";
 57         }
 58 
 59         location ~* ^/Abc {
 60            echo "abc";
 61         }
 62 
 63         location ^~ /AAA {
 64            echo "AAA";
 65         }

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

location = /test {
      echo "TEST";
 }

那么下面的内容可匹配

  • http://192.168.220.9/test
  • http://192.168.220.9/test?gdffgfjd

下面的则无法匹配

  • http://192.168.220.9/test/
  • http://192.168.220.9/test/fdfgdfgdgff

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

  location ~ ^/abc {
       echo "tset";
  }

那么下面的内容可匹配

  • http://192.168.220.9/abc
  • http://192.168.220.9/abc?gdgf=21

下面的则无法匹配

  • http://192.168.220.9/abc/
  • http://192.168.220.9/ABC

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

  location ~* ^/Abc {
       echo "abc";
  }

那么下面的内容可匹配

  • http://192.168.220.9/Abc
  • http://192.168.220.9/Abc?fde

下面的则无法匹配

  • http://192.168.220.9/Abc/
  • http://192.168.220.9/Abcddf

^~:表示指定的正则表达式匹配前缀

 location ^~ /AAA {
         echo "AAA";
 }

那么下面的内容可匹配

  • http://192.168.220.9/AAA
  • http://192.168.220.9/AAA/fdgre

下面的则无法匹配

  • http://192.168.220.9/Afwfs
  • http://192.168.220.9/AAvv

默认的,匹配默认的网页

   location / {
        root   html;
        index  index.html index.htm;
 }
访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数就写多条
deny:设定禁止哪台或哪些主机访问,多个参数就写多条
示例:

allow 192.168.1.1/32;
deny all;

修改配置文件

[root@localhost nginx-1.20.1]# vim /usr/local/nginx/conf/nginx.conf
......
 46         location / {
 47            deny 192.168.220.1   # 拒绝192.168.220.1 主机访问
 48            deny  192.168.1.1;
               allow 192.168.1.0/24;
               allow 10.1.1.0/16;
               allow 2001:0db8::/32;
               deny  all;
               root   html;
 49            index  index.html index.htm;
 50         }
  ......
[root@localhost nginx-1.20.1]# nginx -s reload
 
[root@localhost nginx-1.20.1]# curl 192.168.220.9   # 使用本机访问本机可以
.......
<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>
......

测试,使用192.168.220.1访问被拒绝
在这里插入图片描述

基于用户认证

安装工具包

yum -y install httpd-tools

生成密码

[root@localhost nginx-1.20.1]# htpasswd -c -m /usr/local/nginx/conf/.pass admin(用户)
New password:                              # 输入新密码
Re-type new password:                      # 确认密码
Adding password for user admin
[root@localhost nginx-1.20.1]# cat /usr/local/nginx/conf/.pass    # 查看密码
admin:$apr1$ITMdNM9/$Lk.PM8oMG66ZqIg6tpIYw1

写入配置文件

[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# echo "test page" > test/index.html

[root@localhost ~]# cd /usr/local/nginx/conf/nginx.conf
......
47         location /test {
 48             auth_basic "hello";    # 欢迎信息
 49             auth_basic_user_file ".pass";    # 密码文件
 50             root   html;
 51             index  index.html index.htm;
 52         }
 53 
 54         location / {
 55             root   html;
 56             index  index.html index.htm;
 57         }

 ......
 [root@localhost]# nginx -s reload

访问默认页面
在这里插入图片描述

访问test页面需要输入用户名和密码
在这里插入图片描述
在这里插入图片描述

https配置(一台配置)

生成一对密钥

[root@localhost ~]# cd /etc/pki/
[root@localhost pki]# ls
ca-trust  entitlement  product          rpm-gpg  tls
consumer  java         product-default  rsyslog
[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)

CA生成自签署证书

[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]:school   
Organizational Unit Name (eg, section) []:school
Common Name (eg, your name or your server's hostname) []:school
Email Address []:1@2.com

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

创建目录,客户端生成密钥

[root@localhost CA]# mkdir /usr/local/nginx/conf/ssl

修改配置文件

[root@localhost ~]# vim  /usr/local/nginx/conf/nginx.conf
......
109     server {
110         listen       443 ssl; 
111         server_name  school;   # 修改
112 
113         ssl_certificate      ssl/nginx.crt;    # 修改
114         ssl_certificate_key  ssl/nginx.key;   # 修改
115 
116         ssl_session_cache    shared:SSL:1m;
117         ssl_session_timeout  5m;
118 
119         ssl_ciphers  HIGH:!aNULL:!MD5;
120         ssl_prefer_server_ciphers  on;
121 
122         location / {
123             root   html;
124             index  index.html index.htm;
125         }
126     }
......

[root@localhost ~]# cd /usr/local/nginx/conf/ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
...............................................+++++
....+++++
e is 65537 (0x010001)
[root@localhost ssl]# ls
nginx.key

# 客户端生成证书签署请求
[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]:school
Organizational Unit Name (eg, section) []:school
Common Name (eg, your name or your server's hostname) []:school
Email Address []:1@2.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]# openssl ca -in nginx.csr -out nginx.crt -days 365Using 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 27 12:30:41 2021 GMT
            Not After : Oct 27 12:30:41 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = school
            organizationalUnitName    = school
            commonName                = school
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                52:8C:4D:05:E1:AF:6C:27:48:87:84:62:57:94:F1:19:60:4C:0E:A1
            X509v3 Authority Key Identifier: 
                keyid:B4:02:12:C0:39:5C:FB:CC:A4:FD:26:D5:B4:6D:8F:50:21:28:41:7F

Certificate is to be certified until Oct 27 12:30:41 2022 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]# nginx -s reload

[root@localhost ssl]# ss -antl
State   Recv-Q  Send-Q   Local Address:Port     Peer Address:Port  Process  
LISTEN  0       128            0.0.0.0:443           0.0.0.0:*              
LISTEN  0       128            0.0.0.0:80            0.0.0.0:*              
LISTEN  0       128            0.0.0.0:22            0.0.0.0:*              
LISTEN  0       80                   *:3306                *:*              
LISTEN  0       128               [::]:22               [::]:*

访问测试
在这里插入图片描述
在这里插入图片描述

开启状态页面

开启status:

# 查看nginx是否安装了状态页面的模块
[root@nginx ~]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (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

# 上面的 --with-http_stub_status_module 就是状态页面的模块,下面我们启用它


[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
 43         location / {
 44             root   html;
 45             index  index.html index.htm;
 46         }
 47        
 48        location /status {      # 添加
 49             stub_status;       # 添加
 50        }                       # 添加
......

[root@nginx ~]# nginx -s reload   # 重新加载nginx配置文件

访问nginx状态页面 http://server_ip/status
2
状态页面信息详解:

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

rewrite(重新写入URL重定向)
语法:rewrite regex replacement flag;,如:

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

# 写进配置文件
[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# ls
50x.html  index.html
[root@nginx html]# mkdir images
[root@nginx html]# cd images
[root@nginx images]# ls
1.jpg      # 上传一张图片

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
48        location /images {                   # 添加
49           root html/images;                 # 添加
50           index index.html index.htm;       # 添加
51        }                                    # 添加
.......
[root@nginx]# nginx -s reload

访问图片
在这里插入图片描述
如果图片的文件夹images换了个名字

[root@nginx logs]# cd /usr/local/nginx/html/
[root@nginx html]# ls
50x.html  images  index.html
[root@nginx html]# mv images imgs
[root@nginx html]# ls
50x.html  imgs  index.html              # 将存放图片的文件夹改了个名字叫imgs

再去访问,就会找不到
在这里插入图片描述
所以就会用到rewrite(重定向)当找不到原来的内容时重定向到另一个位置
再次修改配置文件用rewrite

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

......
 48        location /images {
 49           rewrite ^/images/(.*\.jpg)$ /imgs/$1;   # 修改,当匹配images时自动重定向到imgs
 50           index  index.html index.htm;
 .......
 [root@nginx]# nginx -s reload

再去访问images目录就会重定向到imgs目录
在这里插入图片描述
此处的$1用于引用(.*.jpg)匹配到的内容:又如

rewrite ^/images/(.*)$ http://images.baidu.com;  # 当匹配到images时,自动重定向到后面的网站

修改配置文件

[root@nginx html]# vim  /usr/local/nginx/conf/nginx.conf
......
 48        location /images {
 49           rewrite ^/images/(.*)$ http://images.baidu.com;    # 修改
 50           index  index.html index.htm;
 51        }
 ......

访问测试
在这里插入图片描述
跳到了我们配置文件中写的网站
在这里插入图片描述

常见的flag

常见的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

last 向后匹配

# 修改配置文件
[root@nginx html]# vim  /usr/local/nginx/conf/nginx.conf
......
 48        location /images {
 49           rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;    # 当匹配到imgs时,因为有last,所以会继续向后匹配
 50        }
 51 
 52        location /imgs {
 53           rewrite ^/imgs/(.*)$ http://images.baidu.com;  # 匹配到这里,这里是写的网站,所以
 54        }
 ......

访问时输出的结果的是网站

在这里插入图片描述
break 终止

# 修改配置文件
[root@nginx html]# vim  /usr/local/nginx/conf/nginx.conf
......
 48        location /images {
 49           rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;    # 当匹配到imgs时,因为有break终止,所以不会继续匹配
 50        }
 51 
 52        location /imgs {
 53           rewrite ^/imgs/(.*)$ http://images.baidu.com;  # 不会匹配到这里
 54        }
 ......

访问结果是图片而不是网站
在这里插入图片描述
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

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

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

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

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

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

if
(具体可看官方文档 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)
语法:if (condition) {...}

应用场景:

  • server段
  • location段

常见的condition

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值