文章目录
- 1. nginx简介
- 2. nginx的特性与优点
- 3. nginx的功能及应用类别
- 4. nginx的模块与工作原理
- 5. nginx的安装与配置
- 6 nginx的配置文件详解
1. 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网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
2. nginx的特性与优点
2.1 nginx的特性
nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:
- 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
- 使用epoll and kqueue作为开发模型
- nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
- nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多
2.2 nginx的优点
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中所配置的每个指令将会启动不同的模块去完成相应的工作。
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线程,一个worker线程用来处理n个request。

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

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

5. nginx的安装与配置
5.1 nginx的安装
1. 创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
2. 安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@localhost ~]# yum -y groups mark install 'Development Tools'
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Last metadata expiration check: 0:02:05 ago on Sat 05 Dec 2020 04:11:50 PM CST.
Dependencies resolved.
===============================================
Package Arch Version Repo Size
===============================================
Installing Groups:
Development Tools
Transaction Summary
===============================================
Complete!
3. 创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
4. 下载nginx
[root@localhost ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
[root@localhost ~]# ls
anaconda-ks.cfg nginx-1.18.0.tar.gz
5. 编译安装
[root@localhost ~]# tar xf nginx-1.18.0.tar.gz [root@localhost ~]# ls
anaconda-ks.cfg nginx-1.18.0.tar.gz
nginx-1.18.0
[root@localhost ~]# cd nginx-1.18.0
[root@localhost nginx-1.18.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@localhost nginx-1.18.0]# make -j $(nproc) && make install
5.2 nginx安装后配置
1. 配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# source /etc/profile.d/nginx.sh
[root@localhost ~]# which nginx
/usr/local/nginx/sbin/nginx
//服务控制方式,使用nginx命令
-t //检查配置文件语法
-v //输出nginx的版本
-c //指定配置文件的路径
-s //发送服务控制信号,可选值有{stop|quit|reopen|reload}
-V //编译时使用的参数
2. 启动nginx
[root@localhost ~]# nginx
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
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 [::]:*
- 访问web页面

6 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提供的网站,包括虚拟主机 |
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 位置 级别; //配置错误日志
- daemon off的用法
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# ls
fastcgi.conf nginx.conf
fastcgi.conf.default nginx.conf.default
fastcgi_params scgi_params
fastcgi_params.default scgi_params.default
koi-utf uwsgi_params
koi-win uwsgi_params.default
mime.types win-utf
mime.types.default
[root@localhost conf]# vim nginx.conf
#user nobody;
worker_processes 1;
daemon off; 添加此行
......
此时运行会一直卡在这,同时可以访问网页
[root@localhost conf]# nginx
- 访问网页

此时若终止,则就访问不了网页
[root@localhost conf]# nginx
^C[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
- master_process off 的用法
[root@localhost conf]# ps -ef|grep nginx
root 1749 1 0 14:28 ? 00:00:00 nginx: master process nginx
nginx 1750 1749 0 14:28 ? 00:00:00 nginx: worker process
root 1757 1550 0 14:28 pts/0 00:00:00 grep --color=auto nginx
[root@localhost conf]# vim nginx.conf
#user nobody;
worker_processes 1;
master_process off; 添加此行
......
[root@localhost conf]# nginx -s stop 先停止
[root@localhost conf]# nginx 再次启动
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@localhost conf]# ps -ef|grep nginx
root 1762 1 0 14:32 ? 00:00:00 nginx 此时就没有master-process了
root 1765 1550 0 14:32 pts/0 00:00:00 grep --color=auto nginx
- error_log 的用法
[root@localhost conf]# vim nginx.conf
error_log logs/error.log; 取消注释,打开日志功能
#error_log logs/error.log notice;
#error_log logs/error.log info;
[root@localhost conf]# nginx -s stop 先停止
[root@localhost conf]# nginx 再启动
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@localhost conf]# ls ../logs/
error.log nginx.pid
[root@localhost conf]# tail -f ../logs/error.log 此时查看日志没有任何输出,一直卡在这
- 此时访问一个不存在的网页

[root@localhost conf]# tail -f ../logs/error.log 此时日志就有输出内容
2020/12/16 14:39:44 [error] 1771#0: *1 open() "/usr/local/nginx/html/hadsjk" failed (2: No such file or directory), client: 192.168.50.1, server: localhost, request: "GET /hadsjk HTTP/1.1", host: "192.168.50.158"
该内容表示的意思依次是:时间,错误日志级别,进程号,open打开/usr/local/nginx/html/hadsjk文件,失败了,因为没有这个内容,是192.168.50.1来访问我的,来访问我的本机,访问资源,用HTTP1.1的协议,
error_log里的位置和级别能有以下可选项:
| 位置 | 级别 |
|---|---|
| file stderr syslog:server=address[,parameter=value] memory:size | debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg |
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 USERNAME [GROUPNAME]的用法
[root@localhost conf]# vim nginx.conf
user nobody; 取消注释
worker_processes 1;
[root@localhost conf]# nginx -s stop
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@localhost conf]# nginx
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@localhost conf]# ps -ef|grep nginx
root 1824 1 0 15:10 ? 00:00:00 ngin: master process nginx
nobody 1825 1824 0 15:10 ? 00:00:00 ngin: worker process 之前默认是nginx,取消注释后就是nobody
root 1834 1550 0 15:11 pts/0 00:00:00 grep --color=auto nginx
- pid的用法
[root@localhost conf]# vim nginx.conf
......
pid logs/nginx.pid; 指定pid文件存放路径
......
[root@localhost conf]# !ps 此时进程已启动
ps -ef|grep nginx
root 1840 1 0 15:13 ? 00:00:00 ngin: master process nginx
nginx 1841 1840 0 15:13 ? 00:00:00 ngin: worker process
root 1845 1550 0 15:14 pts/0 00:00:00 grep --color=auto nginx
[root@localhost conf]# ls /usr/local/nginx/logs/ 进程启动后就有这个pid文件了
error.log nginx.pid
- worker_rlimit_nofile number的用法
[root@localhost conf]# vim nginx.conf
......
worker_rlimit_nofile 655350; 添加此行
......
查看语法是否有错误
[root@localhost 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@localhost conf]# nginx -s stop
[root@localhost conf]# nginx
[root@localhost conf]# ulimit -n
1024 系统内核默认就是1024
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值
- nice值
先查看nice值
[root@localhost ~]# ps -elf|grep nginx 此时nice值为0
1 S root 1862 1 0 80 0 - 20050 - 15:29 ? 00:00:00 nginx: master process nginx
5 S nginx 1863 1862 0 80 0 - 27931 do_epo 15:29 ? 00:00:00 nginx: worker process
0 S root 1871 1550 0 80 0 - 12091 core_s 15:40 pts/0 00:00:00 vim nginx.conf
0 S root 1914 1650 0 80 0 - 3027 - 16:27 pts/1 00:00:00 grep --color=auto nginx
添加nice值
[root@localhost conf]# vim nginx.conf
......
worker_priority -20; 添加此行设置nice值,nice值范围:-20~19
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
再次查看nice值
[root@localhost ~]# ps -elf|grep nginx 此时nice值为-20
1 S root 1862 1 0 80 0 - 20085 - 15:29 ? 00:00:00 nginx: master process nginx
5 S nginx 1917 1862 0 60 -20 - 27960 do_epo 16:31 ? 00:00:00 nginx: worker process
0 R root 1919 1650 0 80 0 - 3027 - 16:31 pts/1 00:00:00 grep --color=auto nginx
6.5 事件相关的配置:event{}段中的配置参数
accept_mutex {off|on}; //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file; //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll]; //指明使用的事件模型,建议让nginx自行选择
worker_connections #; //每个进程能够接受的最大连接数
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.6.1 案例
公司开发了一款app,需要在app上连接服务器,在服务器里面下载文件到客户端里去,但当时怎么都下载不下来。
我发现是因为文件太大,所以就把长连接超时时间调大,但不能调太大,同时也要双管齐下,把公司服务端带宽调高。
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 80;
server_name www.idfsoft.com;
root "/vhosts/web";
}
listen:指定监听的地址和端口
listen address[:port];
listen port;
server_name NAME […]; 后面可跟多个主机,名称可使用正则表达式或通配符
当有多个server时,匹配顺序如下:
- 先做精确匹配检查
- 左侧通配符匹配检查,如*.idfsoft.com
- 右侧通配符匹配检查,如mail.*
- 正则表达式匹配检查,如~ ^.*.idfsoft.com$
- default_server
root path; 设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径
alias path; 用于location配置段,定义路径别名
index file; 默认主页面
index index.php index.html;
error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html
[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html
log_format 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
//注意:此处可用变量为nginx各模块内建变量
location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//语法:location [ 修饰符 ] pattern {......}
6.9.1 nginx平滑升级
- 此时能正常访问网页

- 添加一个echo
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location \test{ 添加此三行,输入hehe
echo 'hehe';
}
#error_page 404 /404.html;
......
检查语法
[root@localhost conf]# nginx -t
nginx: [emerg] unknown directive "echo" in /usr/local/nnx/conf/nginx.conf:51 这里报错,因为无法识别echo,一旦添加了echo模块后就可以识别了。echo模块是第三方的,不是官方的。所以在编译的时候通过echo模块添加进去,意思是原本没这个功能,现在添加一个功能进去
nginx: configuration file /usr/local/nginx/conf/nginx.cf test failed
- 先确认原版本编译了哪些参数(nginx -V)
[root@localhost conf]# nginx -V
nginx version: nginx/1.18.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1c FIPS 28 May 2019 (running wi OpenSSL 1.1.1g FIPS 21 Apr 2020)
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nnx --group=nginx --with-debug --with-http_ssl_module --th-http_realip_module --with-http_image_filter_module -ith-http_gunzip_module --with-http_gzip_static_module -ith-http_stub_status_module --http-log-path=/var/log/ngx/access.log --error-log-path=/var/log/nginx/error.log
- 下载新模块
模块官方


[root@localhost ~]# ls
anaconda-ks.cfg nginx-1.18.0.tar.gz
echo-nginx-module-master.zip
解压zip包
[root@localhost ~]# yum -y install unzip
[root@localhost ~]# unzip echo-nginx-module-master.zip
[root@localhost ~]# ls
anaconda-ks.cfg
echo-nginx-module-master
echo-nginx-module-master.zip
nginx-1.18.0.tar.gz
解压nginx包
[root@localhost ~]# tar xf nginx-1.18.0.tar.gz
[root@localhost ~]# ls
anaconda-ks.cfg nginx-1.18.0
echo-nginx-module-master nginx-1.18.0.tar.gz
echo-nginx-module-master.zip
- 编译新模块,在原有的参数后面加上–add-module=新模块路径
添加模块
[root@localhost ~]# cd nginx-1.18.0
[root@localhost nginx-1.18.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 使用nginx -V 来查找编译的参数,并复制到这里等待从新编译
[root@localhost nginx-1.18.0]# ./configure --help 使用--help来查找加添模块
......
--add-module=PATH enable external module 添加模块模式,后面跟上路径
......
[root@localhost nginx-1.18.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master 在最后面添加模块,..表示上一级目录,在加上解压后的目录
使用make编译,编译后绝不能再安装(make install)
[root@localhost nginx-1.18.0]# make
此时查看编译参数就有新加进去的模块
[root@localhost nginx-1.18.0]# ls
auto conf html man src
CHANGES configure LICENSE objs
CHANGES.ru contrib Makefile README
[root@localhost nginx-1.18.0]# cd objs/
[root@localhost objs]# ls
addon nginx ngx_auto_headers.h src
autoconf.err nginx.8 ngx_modules.c
Makefile ngx_auto_config.h ngx_modules.o
[root@localhost objs]# ./nginx -V
nginx version: nginx/1.18.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1g FIPS 21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
- 备份原程序
[root@localhost ~]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ls
nginx
[root@localhost sbin]# cp nginx{,-mq} 备份
[root@localhost sbin]# ls
nginx nginx-mq
- 停止服务
- 拷贝新程序替换原程序
- 启动服务
使用一条命令解决
[root@localhost objs]# pwd
/root/nginx-1.18.0/objs
[root@localhost objs]# ls
addon nginx ngx_auto_headers.h src
autoconf.err nginx.8 ngx_modules.c
Makefile ngx_auto_config.h ngx_modules.o
[root@localhost objs]# /usr/local/nginx/sbin/nginx -s stop;\cp nginx /usr/local/nginx/sbin/;/usr/local/nginx/sbin/nginx
[root@localhost objs]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
此时再次查看编译参数就有新添加的模块,表示添加模块成功
[root@localhost objs]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.18.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1g FIPS 21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
此时再在配置文件里添加echo
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test {
echo 'hehe';
}
#error_page 404 /404.html;
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时使用cmd来查看是否有内容输出,直接在网页上访问是访问不到的
- 到这里就表示写的location没问题

常用修饰符说明:
| 修饰符 | 功能 |
|---|---|
| = | 精确匹配 |
| ~ | 正则表达式模式匹配,区分大小写 |
| ~* | 正则表达式模式匹配,不区分大小写 |
| ^~ | 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式 |
| @ | 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等 |
没有修饰符表示必须以指定模式开始,如:
[root@localhost conf]# vim nginx.conf
......
location /abc { 这里添加的location没有修饰符,就光一个/abc
echo 'hehe';
}
#error_page 404 /404.html;
......
重新读取文件
[root@localhost conf]# nginx -s reload
- 此时能匹配abc并输出内容,如下几种情况

=:表示必须与指定的模式精确匹配,如:
[root@localhost conf]# vim nginx.conf
......
location = /abc { 在/abc前面添加修饰符 =
echo 'hehe';
}
#error_page 404 /404.html;
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时能匹配abc并输出内容,如以下几种情况

- 以下几种情况不能匹配

~:表示指定的正则表达式要区分大小写,如:
[root@localhost conf]# vim nginx.conf
......
server {
location ~ ^/abc$ {
echo 'hehe';
}
#error_page 404 /404.html;
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时能匹配abc并输出内容,如以下几种情况

- 以下几种情况不能匹配

~*:表示指定的正则表达式不区分大小写,如:
[root@localhost conf]# vim nginx.conf
......
location ~* ^/abc$ { 在上一步多添加一个*
echo 'hehe';
}
#error_page 404 /404.html;
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时能匹配abc并输出内容,如以下几种情况

- 以下几种情况不能匹配

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式
[root@localhost conf]# vim nginx.conf
......
location /abc { 这个没有修饰符
echo haha;
}
location ~* ^/abc$ { 这个有修饰符
echo 'hehe';
}
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时匹配abc,看输出结果怎样

查找顺序和优先级:由高到底依次为
- 带有=的精确匹配优先
[root@localhost conf]# vim nginx.conf
......
location /abc {
echo haha;
}
location ~* ^/abc$ {
echo 'hehe';
}
location = /abc { 这里带有=的修饰符写在最后面
echo '好好学习';
}
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时匹配abc并输出内容

- 正则表达式按照他们在配置文件中定义的顺序
- 带有^~修饰符的,开头匹配
[root@localhost conf]# vim nginx.conf
......
location /abc {
echo haha;
}
location ~* ^/abc$ {
echo 'hehe';
}
location ~^/abc { 此时这个修饰符写在最后面
echo '天天向上';
}
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 此时匹配abc并输出内容:hehe

[root@localhost conf]# vim nginx.conf
......
location /abc {
echo haha;
}
location ~^/abc { 此时这个修饰符写在中间
echo '天天向上';
}
location ~* ^/abc$ { 这个正则表达式和第二个正则表达式,谁写在前面就输出谁
echo 'hehe';
}
......
重新读取配置文件
[root@localhost conf]# nginx -s reload
- 匹配abc并输出内容:天天向上

- 带有或*修饰符的,如果正则表达式与URI匹配
- 没有修饰符的精确匹配
优先级次序如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )
6.10 访问控制
用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:
allow 192.168.1.1/32 172.16.0.0/16;
deny all;
- 例子
[root@localhost ~]# cd /usr/local/nginx/html
[root@localhost html]# ls
50x.html index.html
[root@localhost html]# mkdir test
[root@localhost html]# ls
50x.html a.html index.html test
[root@localhost html]# mv a.html test/index.html
[root@localhost html]# ls
50x.html index.html test
[root@localhost html]# ls test/
index.html
此时主机可以访问
[root@localhost html]# curl http://192.168.50.158/test/index.html
lhaha
- 能访问test/

- 此时添加location
[root@localhost conf]# vim nginx.conf
......
location /test {
root /usr/local/nginx/html;
index index.html;
}
......
[root@localhost conf]# nginx -s reload
- 此时依然可以访问test/

- 添加允许访问主机(白名单)
[root@localhost conf]# vim nginx.conf
......
location /test {
root /usr/local/nginx/html;
index index.html;
allow 192.168.50.158/32; 只允许这台主机访问
deny all; 拒绝所有主机
}
......
这两行内容写到哪儿就影响哪儿,比如写到location里指挥影响location,写到server下面会影响所有location,写到http下面则影响所有location
[root@localhost conf]# nginx -s reload
- 此时可以在主机上访问,其他主机不能访问
[root@localhost html]# curl http://192.168.50.158/test/index.html
lhaha

3. 添加允许访问的主机(黑名单)
[root@localhost conf]# vim nginx.conf
......
location /test {
root /usr/local/nginx/html;
index index.html;
deny 192.168.50.158/32;
allow all;
}
......
[root@localhost conf]# nginx -s reload
- 此时该主机不能访问,其他主机可以访问
[root@localhost html]# curl http://192.168.50.158/test/index.html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

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
- 例子
[root@localhost nginx]# pwd
/usr/local/nginx
[root@localhost nginx]# ls
client_body_temp html sbin
conf logs scgi_temp
fastcgi_temp proxy_temp uwsgi_temp
[root@localhost nginx]# htpasswd -c -m /usr/local/nginx/.password admin
New password: 自己设密码,123456
Re-type new password:
Adding password for user admin
[root@localhost nginx]# ls -a
. conf logs sbin
.. fastcgi_temp .password scgi_temp
client_body_temp html proxy_temp uwsgi_temp
[root@localhost nginx]# cat .password
admin:$apr1$DmCmYnIs$5Zoha.gR1FTOniLMOi9Ih0 用户名:加密后的密码
在配置文件里添加内容
[root@localhost nginx]# vim conf/nginx.conf
......
location /test {
root /usr/local/nginx/html;
index index.html;
auth_basic "gege"; 这两行也在哪儿就会影响哪儿,跟访问控制效果相同
auth_basic_user_file '/usr/local/nginx/.password';
}
......
[root@localhost nginx]# nginx -s reload
- 访问网页


6.12 https配置
生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:
server {
listen 443 ssl;
server_name www.idfsoft.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
6.12.1 例子
生成证书
1. CA生成一对密钥
[root@nginx ~]# mkdir /etc/pki/CA
[root@nginx ~]# cd /etc/pki/CA/
[root@nginx CA]# mkdir private
[root@nginx CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048) #生成密钥,括号必须要
Generating RSA private key, 2048 bit long modulus (2 primes)
...............................+++++
...........................................+++++
e is 65537 (0x010001)
[root@nginx CA]# openssl rsa -in private/cakey.pem -pubout #提取公钥
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw0v4NXHn2Uzr+9hVxET+
LsK7iD8DaSQoFDUtyT2VAkdnbRx5YiMsdm80xVUFPE/Yfux5re4HClWsvj19IkzP
/nOHAr/53kbTQBl17t1Yl/oZuyZ9Vvf5XbYMKZ7MAQ55xi6wGKeIUyUu1oQ5lENh
aXeIVAurgUT8e7X7TdrH5iJ0pscUuRE0i/JGEF2kZeAS7Pr7XgKTgZ+seEamYRED
leS68aR2iZGaHYqlz+TfGxkUeUmExn0PnSbwCvfx5n7eZkuTv6H4cOzcWILwZRNI
ezRnSkXIq9wJaAxTMtys1QWpWH1gL/kMGW0nMUot3T23aAvlQqGn7E21i2bippx9
VQIDAQAB
-----END PUBLIC KEY-----
2. CA生成自签署证书
先查看域名
[root@nginx ~]# cd /usr/local/nginx
[root@nginx nginx]# cd conf/
[root@nginx conf]# vim nginx.conf
......
server {
listen 80;
server_name www.example.com; 此处填写域名www.example.com
......
#生成自签署证书
[root@nginx 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]:runtime
Organizational Unit Name (eg, section) []:peixun
Common Name (eg, your name or your server's hostname) []:www.example.com 这里填写前面查看的域名
Email Address []:1@2.com
#读出cacert.pem证书的内容
[root@nginx CA]# openssl x509 -text -in cacert.pem
[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial
3. 客户端生成密钥
如apache就执行这步骤:cd /etc/httpd && mkdir ssl && cd ssl
但此时用的是nginx,所以,执行以下步骤
[root@nginx nginx]# pwd
/usr/local/nginx
[root@nginx nginx]# mkdir ssl
[root@nginx nginx]# cd ssl/
[root@nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.............................+++++
.................+++++
e is 65537 (0x010001)
4. 客户端生成证书签署请求
[root@nginx 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]:runtime
Organizational Unit Name (eg, section) []:peixun
Common Name (eg, your name or your server's hostname) []:www.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 []:
5. 客户端把证书签署请求文件发送给CA
scp httpd.csr root@CA端IP:/root 这里不需要做这步骤,因为我们已经在当前目录了
6.CA签署客户端提交上来的证书
[root@nginx 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: Dec 24 01:55:57 2020 GMT
Not After : Dec 24 01:55:57 2021 GMT
Subject:
countryName = cn
stateOrProvinceName = hb
organizationName = runtime
organizationalUnitName = peixun
commonName = www.example.com
emailAddress = 1@2.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
16:19:50:00:E0:FF:6B:E4:48:CE:B8:23:58:BE:17:64:19:FB:B2:95
X509v3 Authority Key Identifier:
keyid:0F:32:FC:34:E2:2D:56:C7:88:D9:E8:D1:F8:5C:27:F0:A5:73:57:1E
Certificate is to be certified until Dec 24 01:55:57 2021 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@nginx ssl]# ls
nginx.crt nginx.csr nginx.key 生成了证书
[root@nginx ssl]# rm -rf nginx.csr 这个只是过度,没用可以删除
[root@nginx ssl]# ls
nginx.crt nginx.key 生成公钥,私钥
7. 修改配置文件
[root@nginx ~]# cd /usr/local/nginx/conf/
[root@nginx conf]# vim nginx.conf
......
server { 将以下几行注释取消掉
listen 443 ssl;
server_name www.example.com; 这里填写域名
ssl_certificate ../ssl/nginx.crt; 填写公钥和私钥路径
ssl_certificate_key ../ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
}
8. 启动服务
[root@nginx conf]# nginx
[root@nginx conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
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 0.0.0.0:443 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
- 此时可以访问网站

6.13 开启状态界面
开启status:
location /status {
stub_status {on | off};
allow 172.16.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已处理完正在等候下一次请求指令的驻留连接 |
- 例子
添加内容
[root@localhost nginx]# vim conf/nginx.conf
......
location /status {
stub_status on;
}
......
[root@localhost nginx]# nginx -s reload
此时主机可以访问
[root@localhost conf]# curl http://192.168.50.158/status
Active connections: 3
server accepts handled requests
82 82 95
Reading: 0 Writing: 1 Waiting: 2
- 访问网页

活动的连接数:2
服务接受的连接数:58
处理的个数:58
请求的个数:58
处于读的个数:0
处于写的个数:1
处于等待的个数:1
如果需要访问该网页,则需要编译参数这个参数: --with-http_stub_status_module
[root@localhost nginx]# nginx -V
nginx version: nginx/1.18.0
built by gcc 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC)
built with OpenSSL 1.1.1g FIPS 21 Apr 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
- 此时再将法则添加进去,允许哪台主机可以访问(公司里用此种方法,只能自己看到该信息)
[root@localhost nginx]# vim conf/nginx.conf
......
location /status {
stub_status on;
allow 192.168.50.158/32;
deny all;
}
......
重新读取配置文件
[root@localhost nginx]# nginx -s reload
主机可以访问
[root@localhost nginx]# curl http://192.168.50.158/status
Active connections: 3
server accepts handled requests
61 61 60
Reading: 0 Writing: 1 Waiting: 2
- 其他主机不能访问

- 使用zabbix监控时怎么取值
[root@localhost ~]# curl http://192.168.50.158/status
Active connections: 1
server accepts handled requests
65 65 64
Reading: 0 Writing: 1 Waiting: 0
[root@localhost ~]# curl -s http://192.168.50.158/status |awk 'NR==1{print $3}'
1
6.14 rewrite
语法:rewrite regex replacement flag;,如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
6.14.1 例一
1. 创建一个目录
[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# mkdir img
[root@nginx html]# ls
50x.html img index.html
[root@nginx html]# cd img/
[root@nginx img]# ls
[root@nginx img]#
2. 在网上下载一张图片
[root@nginx img]# ls
1.png
[root@nginx img]# mv 1.png 1.jpg 修改名字
[root@nginx img]# ls
1.jpg
- 此时可以在网站上网文这张图片

3. 写一个location
[root@nginx ~]# cd /usr/local/nginx/
[root@nginx nginx]# cd conf/
[root@nginx conf]# vim nginx.conf
......
location /img {
root /usr/local/nginx/html;
}
......
4. 重新加载
[root@nginx conf]# nginx -s reload
- 此时依然可以正常访问

5. 此时开始模拟
修改图片名字
[root@nginx img]# cd ..
[root@nginx html]# ls
50x.html img index.html
[root@nginx html]# mv img image
[root@nginx html]# ls
50x.html image index.html
- 此时再次用img访问就访问不了

6. 在配置文件里添加location
[root@nginx conf]# vim nginx.conf
......
location /img {
root /usr/local/nginx/html;
}
location /image { 添加这几行
root /usr/local/nginx/html;
}
.......
[root@nginx conf]# nginx -s reload
- 此时还是访问不了

7. 添加rewrite 规则
[root@nginx conf]# vim nginx.conf
......
location /img {
rewrite ^/img/(.*\.jpg)$ /image/$1 break; 添加rewrite规则:img交给image去找,$1等于括号里的内容
}
location /image {
root /usr/local/nginx/html;
}
......
[root@nginx conf]# nginx -s reload
- 此时就可以访问

8. 若此时把图片移到其他位置
[root@nginx html]# ls
50x.html image index.html
[root@nginx html]# mv image /opt/
[root@nginx html]# ls
50x.html index.html
[root@nginx html]# ls /opt/
image
- 此时访问就访问不了

9. 修改图片路径
[root@nginx conf]# vim nginx.conf
......
location /img {
rewrite ^/img/(.*\.jpg)$ /image/$1 break;
}
location /image {
root /opt/; 修改成/opt/
}
......
[root@nginx conf]# nginx -s reload
- 此时还是访问不了,是因为用的/来找,找不到图片路径

10. 此时不用/来找
[root@nginx conf]# vim nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /img {
root /opt; 添加此行
rewrite ^/img/(.*\.jpg)$ /image/$1 break;
}
location /image {
root /opt/;
}
......
[root@nginx conf]# nginx -s reload
- 此时就可以访问

此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
如上例所示,replacement可以是某个路径,也可以是某个URL
6.14.2 例二
1. 写配置文件
[root@nginx conf]# pwd
/usr/local/nginx/conf
[root@nginx conf]# vim nginx.conf
......
location /bbs {
echo 'bbs test.'; 添加这三行
}
......
[root@nginx conf]# nginx -s reload
2. 创建一个bbs目录
[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# mkdir dds
[root@nginx html]# ls
50x.html bbs index.html
- 此时可以用ip访问

3. 添加Location
[root@nginx conf]# vim nginx.conf
......
location /bbs {
root /usr/local/nginx/html; 添加这几行
index index.html index.htm;
}
......
[root@nginx conf]# nginx -s reload
4. 写一个文件
[root@nginx html]# cd bbs
[root@nginx bbs]# ls
[root@nginx bbs]# echo 'bbs test page' > index.html
- 此时可以在网站上看到文件

5. 访问bbs,转到其他网站里去
[root@nginx conf]# vim nginx.conf
......
location /bbs {
rewrite ^/bbs/(.*)$ https://blog.csdn.net/yi_qingjun/article/list/1 ; 后面跟要转的网站地址
}
......
[root@nginx conf]# nginx -s reload
- 此时访问192.168.50.158/bbs就转到其他网站里了

6. 访问img转到其他网址。
这种方意义:别人来访问图片以为是在我的服务器上访问的图片,其实是在第三人的网站上访问的。
[root@nginx conf]# vim nginx.conf
......
location /img {
rewrite ^/img/(.*)$ https://pic.sogou.com/d?query=%E6%95%B0%E7%A0%81%E5%AE%9D%E8%B4%9D&forbidqc=&entityid=&preQuery=&rawQuery=&queryList=&st=&did=1 break;
}
......
[root@nginx conf]# nginx -s reload
此时并没有img文件
[root@nginx html]# pwd
/usr/local/nginx/html
[root@nginx html]# ls
50x.html bbs index.html
- 此时访问192.168.50,158/img会直接跳转到其他网址


常见的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)
6.14.3 例三
添加以下几行
[root@nginx conf]# vim nginx.conf
......
location /img {
root /opt;
rewrite ^/img/(.*\.jpg)$ /image/$1 last;
}
先找img,找不到再找image,再找images
location /image {
root /opt;
rewrite ^/image/(.*\.jpg)$ /images/$1 last;
}
......
[root@nginx conf]# nginx -s reload
修改图片文件名称
[root@nginx html]# cd /opt/
[root@nginx opt]# ls
image
[root@nginx opt]# mv image images
[root@nginx opt]# ls
images
- 此时可以访问

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
| 标识符 | 意义 |
|---|---|
| ^ | 必须以^后的实体开头 |
| $ | 必须以$前的实体结尾 |
| . | 匹配任意字符 |
| [] | 匹配指定字符集内的任意字符 |
| [^] | 匹配任何不包括在指定字符集内的任意字符串 |
| l | 匹配 l之前或之后的实体 |
| () | 分组,组成一组用于匹配的实体,通常会有 l来协助 |
捕获子表达式,可以捕获放在()之间的任何文本,比如:
^(hello|sir)$ //字符串为“hi sir”捕获的结果:$1=hi$2=sir
//这些被捕获的数据,在后面就可以当变量一样使用了
6.15 if
语法:if (condition) {…}
应用场景:
- server段
- location段
常见的condition
-
变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
-
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
-
正则表达式的模式匹配操作
- ~:区分大小写的模式匹配检查
- ~*:不区分大小写的模式匹配检查
- !和!*:对上面两种测试取反
-
测试指定路径为文件的可能性(-f,!-f)
-
测试指定路径为目录的可能性(-d,!-d)
-
测试文件的存在性(-e,!-e)
-
检查文件是否有执行权限(-x,!-x)
6.15.1 基于浏览器实现分离案例
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;
}
6.15.2 防盗链案例
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}
}
6.16 统计某个时间段,Nginx日志访问最频繁的IP
awk '/21\/Dec\/2020/ {ips[$1]++} END {for(i in ips){print ips[i],i}}' access.log | sort -rn | head
[root@Nginx logs]# awk '/21\/Dec\/2020/ {ips[$1]++} END {for(i in ips){print ips[i],i}}' access.log | sort -rn | head
91 192.168.50.138
20 192.168.50.129
10 192.168.50.136
6.17 反向代理与负载均衡
nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。
nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。
但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。
Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache
如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=…/ngx_cache_purge-1.0 …
nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内
在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:
upstream idfsoft.com {
ip_hash;
server 127.0.0.1:9080 weight=5;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:1111;
}
注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,翻墙等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。
定义好upstream后,需要在server段内添加如下内容:
server {
location / {
proxy_pass http://idfsoft.com;
}
}
例子
环境说明:
| 主机 | IP | 安装的服务 |
|---|---|---|
| lb | 192.168.50.158 | nginx |
| RS1 | 192.168.50.154 | httpd |
| RS2 | 192.168.50.153 | httpd |
- 在RS1和RS2上安装服务
[root@RS1 ~]# yum -y install httpd
[root@RS1 ~]# systemctl start httpd
[root@RS1 ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 0.0.0.0:9000 0.0.0.0:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 80 *:3306 *:*
[root@RS2 ~]# yum -y install httpd
[root@RS2 ~]# systemctl start httpd
[root@RS2 ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 100 127.0.0.1:25 0.0.0.0:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
- 生成页面
[root@RS1 ~]# cd /var/www/html
[root@RS1 html]# ls
[root@RS1 html]# echo 'RS1' > index.html
[root@RS1 html]# systemctl stop firewalld
- 访问RS1

[root@RS2 ~]# cd /var/www/html
[root@RS2 html]# ls
[root@RS2 html]# echo 'RS2' > index.html
[root@RS2 html]# systemctl stop firewalld
- 访问RS2

- 配置lb端的配置文件
[root@lb ~]# cd /usr/local/nginx/
[root@lb nginx]# cd conf/
[root@lb conf]# vim nginx.conf
......
#gzip on;
upstream www.runtime.com { 添加这三行
server 192.168.50.154;
server 192.168.50.153;
}
server {
listen 80;
server_name www.example.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / { 这里做修改
proxy_pass http://www.runtime.com;
}
#error_page 404 /404.html;
......
重新读取配置文件
[root@lb conf]# nginx -s reload
- 用lb来访问,查看效果


- 设置RS1访问3次,RS2访问1次
[root@lb conf]# vim nginx.conf
......
#gzip on;
upstream www.runtime.com {
server 192.168.50.154 weight=3; 添加weight=3意味着访问3次,不设置则默认访问1次
server 192.168.50.153;
......
[root@lb conf]# nginx -s reload
- 此时访问3次RS1之后再访问1次RS2,如此循环




- ip_hash的用法
[root@lb conf]# vim nginx.conf
......
upstream www.runtime.com {
ip_hash;
server 192.168.50.154 weight=3;
server 192.168.50.153;
......
[root@lb conf]# nginx -s reload
- 此时访问网页会一致显示RS2,显示谁是随机的,然后一致显示这个值

[root@RS1 html]# curl http://192.168.50.158
RS2
[root@RS1 html]#
[root@RS1 html]# curl http://192.168.50.158
RS2
[root@RS1 html]# curl http://192.168.50.158
RS2
[root@RS1 html]# curl http://192.168.50.158
RS2
[root@RS2 html]# curl http://192.168.50.158
RS2
[root@RS2 html]# curl http://192.168.50.158
RS2
[root@RS2 html]# curl http://192.168.50.158
RS2
[root@RS2 html]# curl http://192.168.50.158
RS2

272

被折叠的 条评论
为什么被折叠?



