nginx

1.nginx简介

Nginx (engine x) 是一个高性能的web反向代理服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。
其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。
Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

2.nginx的特性与优点

2.1 nginx的特性

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

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

2.2 nginx的优点

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

3.nginx的功能及应用类别

3.1 nginx的基本功能

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

3.2 nginx的扩展功能

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

3.3 nginx的应用类别

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

4.nginx的模块与工作原理

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

  • URI:Uniform Resource Indentifier,统一资源标识符。用于定义全局范围内(包括但不仅限于互联网)去标识唯一的、定位一种资源访问路径的方式,或者命名方式,被称作统一资源标识符。这里的统一指的是路径格式上的统一。

  • URL:Uniform Resource Location,统一资源定位符,是URI的一个子集,用于描述在互联网上互联网资源的统一表示格式(protocol://host:port/path/to/file)

  • PV:Page View,打开了多少页面

  • UV:User View,独立IP量(UV的数量多说明访问的人多)

4.1 nginx的模块分类

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

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

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

nginx模块从功能上分为处理器模块过滤器模块代理器模块

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

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

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

4.2 nginx的工作原理

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

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

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

Nginx默认采用多进程工作方式,Nginx启动后,会运行一个master进程和多个worker进程。其中master充当整个进程组与用户的交互接口,同时对进程进行监护,管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。worker用来处理基本的网络事件,worker之间是平等的,他们共同竞争来处理来自客户端的请求。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request
在这里插入图片描述
web sever:web服务器的集群
application server : 应用服务器的集群
mencached: 缓存服务器的集群
backend: 后端
advaced I/O: 同步
sendfile,AIO 异步

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

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

下图展示了nginx模块一次常规的HTTP请求和响应的过程
在这里插入图片描述

4.3 web服务器请求资源的过程

在这里插入图片描述

首先我们客户端发送一个请求到Web服务器,请求首先是到网卡。

网卡将请求交由内核空间的内核处理,其实就是拆包了,发现请求的是80端口。

内核便将请求发给了在用户空间的Web服务器,Web服务器解包发现客户端
请求的index.html页面、

Web服务器便进行系统调用将请求发给内核

内核发现在请求的是一页面,便调用磁盘的驱动程序,连接磁盘

内核通过驱动调用磁盘取得的页面文件

内核将取得的页面文件保存在自己的缓存区域中便通知Web进程或线程来取相应的页面文件

Web服务器通过系统调用将内核缓存中的页面文件复制到进程缓存区域中

Web服务器取得页面文件来响应用户,再次通过系统调用将页面文件发给内核
内核进程页面文件的封装并通过网卡发送出去,当报文到达网卡时通过网络响应给客户端

5.nginx的安装与配置

5.1 nginx的安装

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

//安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make wget
[root@localhost ~]# yum -y groups mark install 'Development Tools'

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

//下载nginx
[root@localhost ~]# wget http://nginx.org/download/nginx-1.21.3.tar.gz
--2021-10-25 23:25:56--  http://nginx.org/download/nginx-1.21.3.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5704::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1066609 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.21.3.tar.gz”

nginx-1.21.3.tar.gz       100%[=====================================>]   1.02M  28.3KB/s  用时 32s     

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

//编译安装
[root@localhost ~]# ls 
anaconda-ks.cfg  nginx-1.21.3.tar.gz
[root@localhost ~]# tar xf nginx-1.21.3.tar.gz 
[root@localhost ~]# cd nginx-1.21.3/
[root@localhost nginx-1.21.3]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log

[root@localhost nginx-1.21.3]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

5.2 nginx安装后配置

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

//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload},一般只用到stop和reload
	-V  //显示nginx服务器的版本号和nginx服务器的编译情况
	-h  //打印二进制文件nginx的用法
	-t -q //一起使用,如果配置文件无错误,将无任何输出
	-p  //用来改变nginx的安装路径,常用在平滑升级Nginx服务器的场合
	-g //用来补充nginx配置文件,向nginx服务指定启动时应用于全局的配置

//启动nginx,无需-s指定
[root@localhost ~]# nginx 
[root@localhost ~]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

//-v输出nginx的版本
[root@localhost ~]# nginx -v
nginx version: nginx/1.21.3

//-V输出nginx的版本和编译安装nginx的命令,可以查看安装了哪些模块
[root@localhost ~]# nginx -V
nginx version: nginx/1.21.3
built by gcc 8.4.1 20200928 (Red Hat 8.4.1-1) (GCC) 
built with OpenSSL 1.1.1g FIPS  21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

//-h列出帮助文档
[root@localhost ~]# nginx -h
nginx version: nginx/1.21.3
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: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file

//-t检查安装目录下/conf/nginx.conf文件语法
[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 ~]# cp /usr/local/nginx/conf/nginx.conf /opt/
[root@localhost ~]# cp /usr/local/nginx/conf/mime.types /opt/
[root@localhost ~]# ls /opt/
mime.types  nginx.conf		//修改拷贝到其他位置的配置文件nginx.conf
[root@localhost ~]# nginx -s stop;nginx -c /opt/nginx.conf 	//停止,然后马上启动,-c指定修改的配置文件nginx.conf
[root@localhost ~]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         
//如果配置文件修改有误,取消-c,使用默认的配置文件
[root@localhost ~]# nginx -s stop;nginx 

6 nginx的配置文件详解

主配置文件:安装目录/conf/nginx.conf

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

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

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

6.1 nginx.conf配置详解

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

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

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

derective value1 [value2 ...];

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value

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

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

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

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

级别越低记录的越详细
位置一般用的是file文件
级别一般默认的是error

6.3 正常运行必备的配置参数

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

参数user和group(可选)

//nginx安装过后配置文件中的user默认是nobody,但是配置文件中user参数是注释掉的,即使我们把注释去掉,默认user也不是nobody,是nginx
[root@localhost ~]# head -3 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  1;
[root@localhost ~]# ps -ef |grep nginx
root       43320       1  0 08:23 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43321   43320  0 08:23 ?        00:00:00 nginx: worker process
root       43407    1434  0 08:23 pts/0    00:00:00 grep --color=auto nginx

参数worker_rlimit_nofile number
Linux是有文件句柄限制的(open files),一般默认是1024,当超过这个数量便会报 Too many open files错误,修改nginx参数worker_rlimit_nofile number时,同时也需要修改系统的open file,使用命令ulimit -a可以查看句柄数

[root@localhost ~]# ulimit -a
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 3026
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024	//句柄数
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 3026
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

//修改nginx配置文件worker_rlimit_nofile number为65535
[root@localhost ~]# head -5 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  1;

worker_rlimit_nofile 65535;
[root@localhost ~]# nginx -s stop;nginx 

//修改系统允许打开的文件数,修改系统配置文件
[root@localhost ~]# tail -3 /etc/security/limits.conf 
# End of file	//最后添加下面两行
* soft nofile 65535             
* hard nofile 65535
#重启或重新打开终端

6.4 优化性能的配置参数

worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值
  • 参数worker_processes nworker_cpu_affinity cpumask
//查看CPU核数
top - 08:47:49 up 36 min,  2 users,  load average: 0.06, 0.07, 0.07
Tasks: 203 total,   1 running, 202 sleeping,   0 stopped,   0 zombie
%Cpu0  :  0.7 us,  1.3 sy,  0.0 ni, 97.7 id,  0.0 wa,  0.0 hi,  0.3 si,  0.0 st
%Cpu1  :  0.3 us,  2.0 sy,  0.0 ni, 97.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :    791.5 total,    115.1 free,    271.1 used,    405.3 buff/cache
MiB Swap:   2048.0 total,   2040.7 free,      7.2 used.    383.2 avail Mem 

//配置参数
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# head -4 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
[root@localhost ~]# nginx -s stop;nginx 

使用top命令查看nginx运行
输入top命令之后按L搜索nginx,然后再按f
在这里插入图片描述
按f之后,空格开启下面这个功能,然后q退出
在这里插入图片描述
此时可以查看到nginx进程对应一个核心
在这里插入图片描述

  • 参数worker_priority
    安装后默认优先级是0,可以再配置文件中修改优先级(优先级越高获得更多的CPU运行时间,更优先获得CPU运行的机会)
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# head -6 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
worker_rlimit_nofile 65535;
worker_priority -20;		//修改优先级为-20
[root@localhost ~]# nginx -s stop;nginx 
#优先级有-20到19,分别对应100到139

在这里插入图片描述

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

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

一个进程最大并发量最大为50000,但是实际配置时一般设为30000
并发量=(worker_processes*worker_connections)/2

配置并发量为30000

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

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
worker_rlimit_nofile 65535;
worker_priority -20;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  30000;
}
[root@localhost ~]# nginx -s stop;nginx 

6.6 网络连接相关的配置参数

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;    //发送响应报文的超时时长

6.7 fastcgi的相关配置参数

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

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

6.8 常需要进行调整的参数

  • worker_processes
  • worker_connections
  • worker_cpu_affinity
  • worker_priority

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

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

http {//协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {//负载均衡配置
    ...
  }
  server {//服务器级别,每个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 test.example.com;

        location / {
            root   html/test;
            index index.html;
        }
    }
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# echo 'test' > test/index.html
[root@localhost html]# nginx -s stop;nginx 
[root@localhost html]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:81                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

在这里插入图片描述
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配置段,定义路径别名

[root@localhost ~]# mkdir -p /var/www/html
[root@localhost ~]# cd /var/www/html
[root@localhost html]# mv /usr/local/nginx/html/test/ .
[root@localhost html]# ls
test
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
   server {
        listen 81;
        server_name test.example.com;

        location / {
            alias  /var/www/html/;	//写绝对路径
            index index.html index.htm;
        }
    }
[root@localhost ~]# nginx -s stop;nginx

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 ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
#取消下面一行的注释,当访问的资源不存在,状态码为404时,用安装目录下html/404.html文件来响应
49         error_page  404              /404.html;

[root@localhost ~]# cd /usr/local/nginx/html/		//在html目录下定义404.html文件
[root@localhost html]# ls
 404.html   50x.html  '第十二章 http协议_忘情OK_51CTO博客_files'   index.html
 
 //重启nginx
[root@localhost html]# nginx -s stop;nginx
[root@localhost html]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

定义完错误页面,此时就会访问到定义的404.html,但是状态码还是404
在这里插入图片描述
指定状态码

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
49         error_page  404   =200           /404.html;	//加上 =(状态码)
[root@localhost ~]# nginx -s stop;nginx

此时访问,状态码就变成你设置的状态码
在这里插入图片描述

  • log_format 定义日志格式
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
//取消下面的注释
 23     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 24                       '$status $body_bytes_sent "$http_referer" '
 25                       '"$http_user_agent" "$http_x_forwarded_for"';
 26 
 27     access_log  logs/access.log  main;
[root@localhost ~]# nginx -s stop;nginx

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

//查看日志
[root@localhost ~]# tail -f /usr/local/nginx/logs/access.log 
192.168.237.1 - - [28/Oct/2021:17:39:08 +0800] "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" "-"

//参数详解
    $remote_addr     //客户端
    $remote_user      //远程用户,没有做认证的默认为 -
    [$time_local]        //本地时间
    $request            //请求方法,协议版本
    $status           //状态码
    $body_bytes_sent     //发送主体字节数,若是从缓存获取就是0
    $http_referer          //是否跳转,如果不是跳转就是 -
    $http_user_agent    //用户代理,即浏览器
    $http_x_forwarded_for    //从哪里跳转,没有跳转为0

//注意:此处可用变量为nginx各模块内建变量,如果不需要某一变量可以自行删除
  • 平滑升级
    为nginx添加新的功能,但是不能影响用户的体验,所以就要掌握平滑升级的方法

平滑升级步骤:不能进行安装操作
(1)、获取老版本的编译参数 -V
(2)、获取新版本或新功能的软件包
(3)、对新功能或新版本的软件包进行编译
(4)、备份老程序
(5)、停掉老程序并用新程序使用老程序的配置文件进行启动
(6)、检验功能,若无问题即用新程序替换老程序

添加echo功能来演示平滑升级
1、获取老版本编译参数、

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

2、获取新功能的软件包

[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module-master.zip  nginx-1.20.1.tar.gz
[root@localhost ~]# tar xf nginx-1.20.1.tar.gz
[root@localhost ~]# unzip echo-nginx-module-master.zip 
[root@localhost ~]# ls
anaconda-ks.cfg           echo-nginx-module-master.zip  nginx-1.20.1.tar.gz
echo-nginx-module-master  nginx-1.20.1

3、对新功能或新版本的软件包进行编译

[root@localhost ~]# cd nginx-1.20.1/
//在老程序编译参数上加了--add-module=../echo-nginx-module-master
[root@localhost nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master

[root@localhost nginx-1.20.1]# make

//编译完成之后会有一个objs目录
[root@localhost nginx-1.20.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
//objs目录下有一个主程序
[root@localhost nginx-1.20.1]# cd objs/
[root@localhost objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src
[root@localhost objs]# ll nginx /usr/local/nginx/sbin/nginx 	//和老程序对比
-rwxr-xr-x  1 root root 6829960 10月 28 18:06 nginx
-rwxr-xr-x. 1 root root 6307576 10月 27 08:16 /usr/local/nginx/sbin/nginx

4、备份老程序

[root@localhost ~]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost ~]# ls /opt/
nginx

5、停掉老程序并用新程序使用老程序的配置文件进行启动

[root@localhost nginx-1.20.1]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.20.1]# ps -ef|grep nginx
root       65655       1  0 18:11 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx      65656   65655  0 18:11 ?        00:00:00 nginx: worker process
nginx      65657   65655  0 18:11 ?        00:00:00 nginx: worker process
root       65913   43765  0 18:11 pts/0    00:00:00 grep --color=auto nginx

//添加一个location来测试echo功能
[root@localhost nginx-1.20.1]# vim /usr/local/nginx/conf/nginx.conf
......
        location /abc {
            echo "hello";
        }

//检查语法
[root@localhost nginx-1.20.1]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

6、检验功能,若无问题即用新程序替换老程序

//检验功能
[root@localhost nginx-1.20.1]# objs/nginx -s reload
[root@localhost ~]# curl http://192.168.237.170/abc
hello

//新程序替换老程序
[root@localhost nginx-1.20.1]# \cp objs/nginx /usr/local/nginx/sbin/nginx 
[root@localhost nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx 
-rwxr-xr-x  1 root root 6829960 10月 28 18:06 objs/nginx
-rwxr-xr-x. 1 root root 6829960 10月 28 18:17 /usr/local/nginx/sbin/nginx

//重启
[root@localhost nginx-1.20.1]# objs/nginx -s stop;nginx
  • location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//域名之后,?之前的为URI
//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

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

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

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

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )
  • 没有修饰符表示必须以指定模式开始
//添加location
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

      location /abc {
            echo "无修饰符的location";
        }
[root@localhost ~]# nginx -s stop;nginx 

//访问匹配
[root@localhost ~]# curl http://192.168.237.170/abc
无修饰符的location
[root@localhost ~]# curl http://192.168.237.170/abc/
无修饰符的location
[root@localhost ~]# curl http://192.168.237.170/abc\?a\=1
无修饰符的location
  • =:表示必须与指定的模式精确匹配
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

        location /abc {
            echo "无修饰符的location";
        }
        location = /abc {
            echo "有等于号的location";
        }

[root@localhost ~]# nginx -s stop;nginx 

//精准匹配URI=abc
[root@localhost ~]# curl http://192.168.237.170/abc
有等于号的location
[root@localhost ~]# curl http://192.168.237.170/abc\?a\=1
有等于号的location
[root@localhost ~]# curl http://192.168.237.170/abc/
无修饰符的location
  • ~:表示指定的正则表达式要区分大小写
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

      location /abc {
            echo "无修饰符的location";
        }
        location ~ ^/abc$ {
            echo "区分大小写的location";
        }
        
[root@localhost ~]# nginx -s stop;nginx 

// ^/abc$,以abc开头和结尾,只能匹配URI=abc,只能是小写
[root@localhost ~]# curl http://192.168.237.170/abc
区分大小写的location
[root@localhost ~]# curl http://192.168.237.170/abc\?a\=1
区分大小写的location
[root@localhost ~]# curl http://192.168.237.170/abcde
无修饰符的location
  • ~*:表示指定的正则表达式不区分大小写
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

       location /abc {
            echo "无修饰符的location";
        }
        location ~ ^/abc$ {
            echo "区分大小写的location";
        }
        location ~* ^/abc$ {
            echo "不区分大小写的location";
        }

[root@localhost ~]# nginx -s stop;nginx 

//不区分大小写的location可以匹配到URI=abc(大小写都可以),但是区分大小写的location放在它上面,所以优先匹配区分大小写的location
[root@localhost ~]# nginx -s stop;nginx
[root@localhost ~]# curl http://192.168.237.170/abc
区分大小写的location
[root@localhost ~]# curl http://192.168.237.170/aBc
不区分大小写的location
[root@localhost ~]# curl http://192.168.237.170/abc/
无修饰符的location

6.10 访问控制

用于location段

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

示例:

//修改配置文件,添加一个location
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            root    html;
            index   index.html;
        }
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# echo 'test page' > test/index.html
[root@localhost html]# nginx -s stop;nginx 

在这里插入图片描述

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

      location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            deny 192.168.237.1;	//禁止该IP访问
            root    html;
            index   index.html;
        }
[root@localhost ~]# nginx -s stop;nginx 

在这里插入图片描述

//添加allow
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            allow 192.168.237.1;	//允许该IP
            deny all;		//禁止所以IP,也就是只能用上面的IP访问该资源
            root    html;
            index   index.html;
        }

[root@localhost ~]# nginx -s stop;nginx 

在这里插入图片描述

6.11 基于用户认证

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

user_auth_file内容格式为:

username:password

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

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

示例

  • 密码放置位置
//这里放置在安装目录下的/conf/下
//使用htpasswd命令生成密码,若没有htpasswd命令。安装httpd-tools包即可
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# htpasswd -c -m .pass admin
New password: 
Re-type new password: 
Adding password for user admin
[root@localhost conf]# cat .pass 
admin:$apr1$WSkKPdH5$1ZhPuvZLGSrrf/eaSQIWp/
  • 修改配置文件
[root@localhost conf]# vim nginx.conf

        location /test {
            auth_basic "欢迎光临";
            auth_basic_user_file ".pass";	//因为密码文件和配置文件同级目录,所以可以直接写相对路径
            root    html;
            index   index.html;
        }
        
[root@localhost conf]# nginx -s stop;nginx 

此配置仅针对test资源有效
在这里插入图片描述
在这里插入图片描述

6.12 https配置

  • 创建密钥放置位置
//这里放置在安装路径下的/conf下
[root@localhost conf]# mkdir ssl
  • 生成私钥
[root@localhost ~]# mkdir /etc/pki/CA
[root@localhost ~]# cd /etc/pki/CA
[root@localhost CA]# mkdir private && (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]:W
Organizational Unit Name (eg, section) []:W
Common Name (eg, your name or your server's hostname) []:test.example.com
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
  • 客户端(例如httpd服务器)生成密钥
[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]:W
Organizational Unit Name (eg, section) []:W
Common Name (eg, your name or your server's hostname) []:test.example.com
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]# ll
总用量 8
-rw-r--r-- 1 root root 1017 10月 28 20:09 nginx.csr
-rw------- 1 root root 1679 10月 28 20:08 nginx.key
  • 客户端把证书签署请求文件发送给CA
    此步骤省略,因为是在一台机器上操作的

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

[root@localhost ssl]# pwd
/usr/local/nginx/conf/ssl
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 28 12:10:53 2021 GMT
            Not After : Oct 28 12:10:53 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = W
            organizationalUnitName    = W
            commonName                = test.example.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                7F:B8:F8:A1:29:B1:E5:38:E4:28:13:D5:A9:C1:8E:65:FD:01:C5:68
            X509v3 Authority Key Identifier: 
                keyid:B5:CA:80:99:DF:33:5E:0E:80:CE:69:07:8E:D8:C0:04:6D:E8:25:64

Certificate is to be certified until Oct 28 12:10:53 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]# ll
总用量 16
-rw-r--r-- 1 root root 4517 10月 28 20:11 nginx.crt
-rw-r--r-- 1 root root 1017 10月 28 20:09 nginx.csr
-rw------- 1 root root 1679 10月 28 20:08 nginx.key

[root@localhost ssl]# rm -f nginx.csr 
  • CA把签署好的证书httpd.crt发给客户端
    此步骤省略,因为是在一台机器上操作的

  • 修改配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
//取消这部分的注释
105     server {
106         listen       443 ssl;
107         server_name  test.example.com;		//改为申请证书时的域名
108 
109         ssl_certificate      ssl/nginx.crt;		//修改crt文件路径
110         ssl_certificate_key  ssl/nginx.key;		//修改key文件路径
111 
112         ssl_session_cache    shared:SSL:1m;
113         ssl_session_timeout  5m;
114 
115         ssl_ciphers  HIGH:!aNULL:!MD5;
116         ssl_prefer_server_ciphers  on;
117 
118         location / {
119             root   html;
120             index  index.html index.htm;
121         }
122     }

[root@localhost ~]# nginx -s stop;nginx

网页访问
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值