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是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:
nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
nginx的模块从结构上分为核心模块、基础模块和第三方模块
用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大
nginx模块从功能上分为三类,分别是:
nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等
具体的指令,请参考nginx的官方文档
nginx的模块直接被编译进nginx,因此属于静态编译方式。
启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。
nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request。

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

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

//nginx 下载地址http://nginx.org/download/nginx-1.22.0.tar.gz 我是提前下好了
[root@nginx ~]# cd /usr/src/
[root@nginx src]# ls
debug kernels nginx-1.22.0.tar.gz
//创建nginx主和组,并创建日志存放目录
[root@nginx src]# useradd -r -M -s /sbin/nologin nginx
[root@nginx src]# mkdir /var/log/nginx
[root@nginx src]# chown -R nginx.nginx /var/log/nginx/
[root@nginx src]# ll -d /var/log/nginx/
drwxr-xr-x. 2 nginx nginx 6 Sep 3 11:50 /var/log/nginx/
//安装依赖包
[root@nginx src]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@nginx src]# tar xf nginx-1.22.0.tar.gz
[root@nginx src]# ls
debug kernels nginx-1.22.0 nginx-1.22.0.tar.gz
[root@nginx src]# cd nginx-1.22.0
//进行编译安装
[root@nginx nginx-1.22.0]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gunzip_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log
[root@nginx nginx-1.22.0]# make && make install
//配置nginx
[root@nginx ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@nginx ~]# source /etc/profile.d/nginx.sh
[root@nginx ~]# nginx
[root@nginx ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@nginx ~]# systemctl disable --now 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 ~]# cd /usr/lib/systemd/system
[root@nginx system]# cp sshd.service nginx.service
[root@nginx system]# vi nginx.service
Documentation=man:sshd(8) man:sshd_config(5)
Wants=sshd-keygen.tar`get
EnvironmentFile=-/etc/crypto-policies/back-ends/opensshserver.config
EnvironmentFile=-/etc/sysconfig/sshd
ExecStart=/usr/local/nginx/sbin/nginx
Restart=on-failure
RestartSec=42s
KillMode=process
[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=/usr/local/nginx/sbin/nginx -s reload
[Install]
WantedBy=multi-user.target
[root@nginx system]# systemctl daemon-reload
[root@nginx system]# systemctl status nginx
● nginx.service - nginx server daemon
Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
Active: inactive (dead)
[root@nginx system]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@nginx system]# nginx -s stop
[root@nginx system]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@nginx system]# systemctl status nginx
● nginx.service - nginx server daemon
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2022-09-03 13:02:19 CST; 3s ago
Process: 39274 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
Main PID: 39275 (nginx)
nginx命令常用选项:
-t //检查配置文件语法
-v //输出nginx的版本
-c //指定配置文件的路径
-s //发送服务控制信号,可选值有{stop|quit|reopen|reload}
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提供的网站,包括虚拟主机 |
文件结构图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3sPbR9IF-1662179846432)(C:\Users\刘昌辉\Desktop\视屏\微信图片_20220903122528.jpg)]
nginx.conf的内容分为以下几段:
每个配置指令要以分号结尾
语法:derective value1 [value2 ...];
配置文件支持使用变量
内置变量:模块会提供内建变量定义
自定义变量:set var_name value
配置运行Nginx服务器用户(组)
指令格式:user user [group];
user:指定可以运行Nginx服务器的用户
group:可选项,可以运行Nginx服务器的用户组
如果user指令不配置或者配置为user nobody nobody,则默认所有用户都可以启动Nginx进程
是否以守护进程方式运行nginx
指令格式:daemon {on|off};
是否以守护进程方式运行nginx,调试时应设置为off
是否以master/worker模型来运行nginx
指令格式:master_process {on|off};
是否以master/worker模型来运行nginx,调试时可以设置为off
worker process数配置
Nginx服务器实现并发处理服务的关键
指令格式:worker_processes number | auto;
number:Nginx进程最多可以产生的worker process数
auto:Nginx进程将自动检测
为了避免上下文切换,通常number值设置为cpu总核心数-1或等于总核心数
将进程绑定到某cpu中,避免频繁刷新缓存
指令格式:worker_cpu_affinity cpumask ...;
cpumask:使用8位二进制表示cpu核心
例:
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
一共四核,0001表示第一个核心,0010表示第二个核心,0100表示第三个核心,1000表示第四个核心
Nginx进程PID存放路径
指令格式:pid file;
file:指定存放路径和文件名称如果不指定默认置于路径 logs/nginx.pid
Nginx进程是作为系统守护进程在运行,需要在某文件中保存当前运行程序的主进程号,Nginx支持该保存文件路径的自定义
错误日志的存放路径
指令格式:error_log 位置 级别;
位置:file | stderr | syslog:server=address[,parameter=value] | memory:size
级别:debug | info | notice | warn | error | crit | alert | emerg
若要使用debug级别,需要在编译nginx时使用--with-debug选项
设置所有worker进程最大可以打开的文件数
指令格式:worker_rlimit_nofile number;
设置所有worker进程最大可以打开的文件数,默认为1024
配置文件的引入
指令格式:include file;
该指令主要用于将其他的Nginx配置或者第三方模块的配置引用到当前的主配置文件中
计时器解析度配置
指令格式:timer_resolution interval;
降低工作过程中计时器解析度,从而减少系统调用次数
例:
timer_resolution 100ms;
worker进程的nice值配置
指令格式:worker_priority number;
定义工作进程的优先级,允许的范围通常从 -20 到 20 变化
设置网络连接的序列化
指令格式:accept_mutex on | off;
该指令默认为on状态,表示会对多个Nginx进程接收连接进行序列化,防止多个进程对连接的争抢。
说到该指令,首先得阐述一下什么是所谓的 “惊群问题”,可以参考 WIKI百科的解释。就Nginx的场景来解释的话大致
的意思就是:当一个新网络连接来到时,多个worker进程会被同时唤醒,但仅仅只有一个进程可以真正获得连接并处理之。
如果每次唤醒的进程数目过多的话,其实是会影响一部分性能的。
所以在这里,如果accept_mutex on,那么多个worker将是以串行方式来处理,其中有一个worker会被唤醒;反之若
accept_mutex off,那么所有的worker都会被唤醒,不过只有一个worker能获取新连接,其它的worker会重新进入休眠状态
这个值的开关与否其实是要和具体场景挂钩的。
是否允许同时接收多个网络连接
指令格式:multi_accept on | off;
该指令默认为off状态,意指每个worker process 一次只能接收一个新到达的网络连接。若想让每个Nginx的
workerprocess都有能力同时接收多个网络连接,则需要开启此配置
事件驱动模型的选择
指令格式:use model;
model模型可选择项包括:select、poll、kqueue、epoll、rtsig等......
最大连接数的配置
指令格式:worker_connections number;
number默认值为512,表示允许每一个worker process可以同时接受的最大连接数
互斥锁锁文件路径配置
指令格式:lock_file file;
nginx 使用锁定机制实现accept_mutex和序列化对共享内存的访问。在大多数系统上,锁都是使用原子操作实现的,并且忽略此指令。在其他系统上,使用"锁定文件"机制。此指令指定锁文件名称的前缀
定义MIME-Type
指令格式:include mime.types;
default_type mime-type;
MIME-Type指的是网络资源的媒体类型,也即前端请求的资源类型
include指令将mime.types文件包含进来
cat mime.types
查看mime.types文件内容,发现其就是一个types结构,里面包含了各种浏览器能够识别的MIME类型以及对应类型的文件后缀名字
自定义服务日志
指令格式:access_log path [format];
path:自定义服务日志的路径
format:可选项,自定义服务日志的字符串格式。其也可以使用 log_format 定义的格式
允许sendfile方式传输文件
指令格式:sendfile on | off;
sendfile_max_chunk size;
前者用于开启或关闭使用sendfile()传输文件,默认off
后者指令若size>0,则Nginx进程的每个workerprocess每次调用sendfile()传输的数据了最大不能超出此值;若size=0则表示不限制。默认值为0
长连接超时时间配置
指令格式:keepalive_timeout timeout [header_timeout];
timeout 表示server端对连接的保持时间,默认75秒
header_timeout 为可选项,表示在应答报文头部的 Keep-Alive 域设置超时时间:“Keep-Alive :timeout = header_timeout”
长连接请求数上限
指令格式:keepalive_requests number;
该指令用于限制用户在一个长连接上所能够允许请求的最大资源数
为指定类型的UserAgent禁用长连接
指令格式:keepalive_disable [msie6|safari|none...];
默认为keepalive_disable msie6;
是否对长连接使用TCP_NODELAY选项
指令格式:tcp_nodelay on|off;
为了提升用户体验,通常设为on,默认为on
读取http请求报文首部的超时时长
指令格式:client_header_timeout number;
定义读取客户端请求标头的超时。如果客户端未在此时间内传输整个标头,则请求将终止 408(请求退出)错误,默认为60s
发送响应报文的超时时长
指令格式:send_timeout time;
设置用于向客户端传输响应的超时。超时仅在两个连续写入操作之间设置,而不是用于传输整个响应。如果客户端在此时间内未收到任何消息,则连接将关闭,默认为60s
定义读取客户端请求正文的超时
指令格式:client_body_timeout time;
超时仅设置为两个连续读取操作之间的一个时间段,而不是为整个请求正文的传输。如果客户端在此时间内未传输任何内容,则请求将终止 408(请求退出)错误,默认为60s
配置网络监听
指令格式:
第一种:配置监听的IP地址:
listen IP[:PORT];
第二种:配置监听的端口:
listen PORT;
例:
listen 192.168.207.129:8080; # 监听具体IP和具体端口上的连接
listen 192.168.207.129; # 监听IP上所有端口上的连接
listen 8080; # 监听具体端口上的所有IP的连接
基于名称和IP的虚拟主机配置
指令格式:server_name name1 name2 ...
name可以有多个并列名称,而且此处的name支持正则表达式书写
例:
server_name ~^www\d+\.myserver\.com$
此时表示该虚拟主机可以接收类似域名 www1.myserver.com 等的请求,而拒绝 www.myserver.com 的域名请求,
所以说用正则表达式可以实现更精准的控制
location配置
指令格式为:location [ = | ~ | ~* | ^~ ] uri {...}
这里的uri分为标准uri和正则uri,两者的唯一区别是uri中是否包含正则表达式
uri前面的方括号中的内容是可选项,解释如下:
“=”:用于标准uri前,要求请求字符串与uri严格匹配,一旦匹配成功则停止
“~”:用于正则uri前,并且区分大小写
“~*”:用于正则uri前,但不区分大小写
“^~”:用于标准uri前,要求Nginx找到标识uri和请求字符串匹配度最高的location后,立即使用此location处理请求,
而不再使用location块中的正则uri和请求字符串做匹配
请求根目录配置
指令格式:root path;
path:Nginx接收到请求以后查找资源的根目录路径
当然,还可以通过alias指令来更改location接收到的URI请求路径,指令为:
alias path;
# path为修改后的根路径
设置网站的默认首页
指令格式:index file ......
file可以包含多个用空格隔开的文件名,首先找到哪个页面,就使用哪个页面响应请求
例:
index.php、index.jsp、index.html...
安装nginx-echo模块 平滑升级
//下载模块
[root@nginx ~]# yum -y install git
[root@nginx ~]# git clone https://github.com/openresty/echo-nginx-module.git
//解压
[root@nginx ~]# tar xf nginx-1.22.0.tar.gz
//查看原来的编译参数
[root@nginx ~]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
//重新编译nginx 只执行make不能执行make install
[root@nginx nginx-1.22.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=/root/echo-nginx-module
//最后添加--add-module=/root/echo-nginx-module
[root@nginx nginx-1.22.0]# make
//停掉原来的nginx 用新编译生成的nginx启动
[root@nginx sbin]# nginx -s stop;~/nginx-1.22.0/objs/nginx -c /usr/local/nginx/conf/nginx.conf
//备份原来的nginx二进制文件
[root@nginx sbin]# pwd
/usr/local/nginx/sbin
[root@nginx sbin]# mv nginx /opt/
//把新编译的nginx复制到当前目录
[root@nginx sbin]# cp ~/nginx-1.22.0/objs/nginx .
[root@nginx sbin]# nginx -V
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=/root/echo-nginx-module
location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
| 修饰符 | 功能 |
|---|---|
| = | 精确匹配 |
| ~ | 正则表达式模式匹配,区分大小写 |
| ~* | 正则表达式模式匹配,不区分大小写 |
| ^~ | 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式 |
| @ | 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等 |
使用正则表达式匹配uri
[root@nginx conf]# pwd
/usr/local/nginx/conf
[root@nginx conf]# vi nginx.conf
location /abc {
echo "没有修饰符";
}
[root@nginx conf]# nginx -s reload
//另一台主机访问
[root@lnmp ~]# curl 192.168.200.5/abc
没有修饰符
[root@lnmp ~]# curl 192.168.200.5/abc\?p1\=11\&p2\=22
没有修饰符
[root@nginx conf]# vi nginx.conf
location = /abc {
echo "使用修饰符";
}
[root@nginx conf]# nginx -s reload
[root@lnmp ~]# curl 192.168.200.5/abc\?p1\=11\&p2\=22
使用修饰符
[root@lnmp ~]# curl 192.168.200.5/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
[root@lnmp ~]# curl 192.168.200.5/abc
使用修饰符
[root@nginx conf]# vi nginx.conf
location ~ ^/abc$ {
echo "正则表达式,区分大小写";
}
[root@nginx conf]# vi nginx.conf
[root@lnmp ~]# curl 192.168.200.5/abc
正则表达式,区分大小写
[root@lnmp ~]# curl 192.168.200.5/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
[root@lnmp ~]# curl 192.168.200.5/abc\?p1\=11\&p2\=22
正则表达式,区分大小写
[root@lnmp ~]# curl 192.168.200.5/ABC
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
[root@nginx conf]# vi nginx.conf
location ~* ^/abc$ {
echo "正则表达式,不区分大小写";
}
[root@nginx conf]# vi nginx.conf
[root@lnmp ~]# curl 192.168.200.5/ABC
正则表达式,不区分大小写
[root@lnmp ~]# curl 192.168.200.5/abc
正则表达式,不区分大小写
[root@lnmp ~]# curl 192.168.200.5/ABC/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
[root@lnmp ~]# curl 192.168.200.5/abc\?p1\=11\&p2\=22
正则表达式,不区分大小写
[root@lnmp ~]# curl 192.168.200.5/ABC\?p1\=11\&p2\=22
正则表达式,不区分大小写
查找顺序和优先级:由高到底依次为
带有=的精确匹配优先
正则表达式按照他们在配置文件中定义的顺序
带有^~修饰符的,开头匹配
带有~或~*修饰符的,如果正则表达式与URI匹配
没有修饰符的精确匹配
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )
访问控制
用于location段
指令格式:allow IP;
deny IP | all;
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
例:
allow 192.168.1.1/32 172.16.0.0/16;
deny all;
用户认证
指令格式:auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"
user_auth_file内容格式为:
username:password
建议用htpasswd来创建user_auth_file文件:
用法:htpasswd -c -m /path/to/.user_auth_file USERNAME
//安装包
[root@nginx ~]# yum -y install httpd-tools
[root@nginx ~]# which htpasswd
/usr/bin/htpasswd
[root@nginx ~]# htpasswd -c -m /usr/local/nginx/conf/.passwd admin
New password:
Re-type new password:
Adding password for user admin
[root@nginx ~]# cat /usr/local/nginx/conf/.passwd
admin:$apr1$c3gZ6lSS$hMY1LINZJeWUQsj9OJeLG0 即加密后的密码
//配置页面
[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# ls
50x.html abc index.html
[root@nginx html]# echo 'abc test' > abc/index.html
[root@nginx conf]# vi nginx.conf
location /abc {
root html;
index index.html;
[root@nginx conf]# nginx -s reload

//配置密码
[root@nginx conf]# vi nginx.conf
location /abc {
auth_basic "jjyy";
auth_basic_user_file /usr/local/nginx/conf/.passwd;
root html;
index index.html;
}
[root@nginx conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf]# nginx -s reload


php要启用fpm模型
配置示例:
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000; //定义反向代理
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
[root@nginx ~]# yum -y install mod_ssl
[root@nginx ~]# vi /etc/httpd/conf.modules.d/00-base.conf
LoadModule ssl_module modules/mod_ssl.so
[root@nginx ~]# openssl genrsa -out server.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
................+++++
.........+++++
e is 65537 (0x010001)
[root@nginx ~]# openssl req -new -key server.key -out server.csr
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]:CH
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:TEST
Organizational Unit Name (eg, section) []:TEST
Common Name (eg, your name or your server's hostname) []:TEST
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@nginx ~]# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Signature ok
subject=C = CH, ST = HB, L = WH, O = TEST, OU = TEST, CN = TEST
Getting Private key
[root@nginx ~]# mv server.crt www.a.com.crt
[root@nginx ~]# mv server.key www.a.com.key
[root@nginx conf]# vi nginx.conf
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /root/www.a.com.crt;
ssl_certificate_key /root/www.a.com.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 conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf]# nginx -s reload

指令格式:
location /status {
stub_status {on | off};
allow 192.168.0.0/16;
deny all;
}
访问状态页面的方式:http://server_ip/status
状态页面信息详解:
| 状态码 | 表示的意义 |
|---|---|
| Active connections 2 | 当前所有处于打开状态的连接数 |
| accepts | 总共处理了多少个连接 |
| handled | 成功创建多少握手 |
| requests | 总共处理了多少个请求 |
| Reading | nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数 |
| Writing | nginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数 |
| Waiting | 开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接 |
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)
常见的flag
| flag | 作用 |
|---|---|
| last | 基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程 |
| break | 中止Rewrite,不再继续匹配一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,且不再会被当前location内的任何rewrite规则所检查 |
| redirect | 以临时重定向的HTTP状态302返回新的URL |
| permanent | 以永久重定向的HTTP状态301返回新的URL |
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)
nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
| 标识符 | 意义 |
|---|---|
| ^ | 必须以^后的实体开头 |
| $ | 必须以$前的实体结尾 |
| . | 匹配任意字符 |
| [] | 匹配指定字符集内的任意字符 |
| [^] | 匹配任何不包括在指定字符集内的任意字符串 |
| | | 匹配 | 之前或之后的实体 |
| () | 分组,组成一组用于匹配的实体,通常会有 | 来协助 |
捕获子表达式,可以捕获放在()之间的任何文本,比如:
^(hello|sir)$ //字符串为“hi sir”捕获的结果:$1=hi$2=sir
//这些被捕获的数据,在后面就可以当变量一样使用了
[root@nginx html]# mkdir image
[root@nginx html]# ls
50x.html abc image index.html
[root@nginx ~]# ls
8a766e44eceb78e3d5421fd8fb7e271a.jpeg nginx-1.20.2.tar.gz www.a.com.crt
anaconda-ks.cfg nginx-1.22.0 www.a.com.key
echo-nginx-module nginx-1.22.0.tar.gz
nginx-1.20.2 server.csr
[root@nginx ~]# mv 8a766e44eceb78e3d5421fd8fb7e271a.jpeg /usr/local/nginx/html/images/1.jpeg
[root@nginx images]# ls
1.jpeg
[root@nginx conf]# vi nginx.conf
location /images {
alias html/images;
}
[root@nginx conf]# nginx -s reload

修改地址继续访问
[root@nginx images]# cd ..
[root@nginx html]# ls
50x.html abc images index.html
[root@nginx html]# mv images imgs
[root@nginx html]# ls
50x.html abc imgs index.html

此时需要用到URL重写
//修改图片名
[root@nginx imgs]# mv 1.jpeg 1.jpg
[root@nginx imgs]# ls
1.jpg
//修改文件
[root@nginx conf]# vi nginx.conf
location /images {
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
location /imgs {
root html;
}
[root@nginx conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf]# nginx -s reload

URL重写就是把原来的位置http://192.168.200.5/images/1.jpg跳转到新位置即http://192.168.200.5/imgs/1.jpg
修改位置
[root@nginx html]# mv imgs /opt/
[root@nginx conf]# vi nginx.conf
location /images {
root /opt;
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
location /imgs {
root html;
}
[root@nginx conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root

#### 网上访问
**修改图片位置让它跳转到百度**
```bash
[root@nginx conf]# vi nginx.conf
location /images {
root /opt;
rewrite ^/images/(.*\.jpg)$ https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E7%A7%91%E6%AF%94&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=1044162770,2158009526&os=328508960,620599900&simid=3372367964,238413971&pn=5&rn=1&di=7117150749552803841&ln=900&fr=&fmq=1662303390062_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fb-ssl.duitang.com%252Fuploads%252Fitem%252F201610%252F15%252F20161015092438_vAUcd.jpeg%26refer%3Dhttp%253A%252F%252Fb-ssl.duitang.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1664895390%26t%3De0cd70985a5a50a28ec74a1c533f2669&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwzLDIsMSw2LDQsNSw3LDgsOQ%3D%3D break;
}
[root@nginx conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf]# nginx -s reload

last应用
[root@nginx conf]# vi nginx.conf //表示只要是访问图片的都自动跳转到百度
location /images {
root /opt;
rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
}
location /imgs {
rewrite ^/imgs/(.*\.jpg)$ http://www.baidu.com last;
}
[root@nginx conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf]# nginx -s reload

语法:if (condition) {...}
应用场景:
常见的condition
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;
}
}
基于浏览器实现分离案例
[root@localhost ~]# cd /usr/local/nginx/html/
创建目录并添加内容
[root@localhost html]# mkdir Gecko chrome firefox
[root@localhost html]# ls
50x.html chrome firefox Gecko index.html
[root@localhost html]# cd chrome/
[root@localhost chrome]# echo 'chrome test page' >index.html
[root@localhost chrome]# cd ..
[root@localhost html]# cd firefox/
[root@localhost firefox]# echo 'firefox test page' >index.html
[root@localhost firefox]# cd ..
[root@localhost html]# cd Gecko/
[root@localhost Gecko]# echo 'Gecko test page' >index.html
[root@localhost html]# tree
.
├── 50x.html
├── chrome
│ └── index.html
├── firefox
│ └── index.html
├── Gecko
│ └── index.html
└── index.html
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
添加以下浏览器内容
location / {
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}
if ($http_user_agent ~ Gecko) {
rewrite ^(.*)$ /Gecko/$1 break;
}
root html;
index index.html index.htm;
}
[root@localhost html]# 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 html]# nginx -s reload
添加浏览器位置
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
location /firefox {
root html;
index index.html;
}
location /chrome {
root html;
index index.html;
}
location /Gecko {
root html;
index index.html;
}
[root@localhost html]# 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 html]# nginx -s reload