本文部分内容参考自Nginx官方文档:http://nginx.org/en/docs/。
学习本章节内容最好拥有一定的计算机知识与Linux基础操作!
一、I/O模型
简单了解I/O模型,最好拥有一定的计算机基础知识。
1.1、I/O是什么?
- I,input,比如键盘按下按钮,输入一个字符,就叫输入。
- O,output,比如输入字符后,在屏幕等设备中打印/显示,这就叫输出。
更多基础知识请自行搜索资料学习,这里不会过多解释。
1.2、I/O模型介绍
阻塞型、非阻塞型、复用型、信号驱动型、异步;此部分知识可以参考本人《并发编程基础知识》,其中同步/异步和阻塞/非阻塞很容易混淆,这点需要注意。
一次文件IO请求,都会由两阶段组成:
第一步:等待数据,即数据从磁盘到内核内存;
第二步:复制数据,即数据内核内存到进程内存;
下面会举一个超市买东西的例子,不是很准确,但是有助于理解。
1.2.1、同步/异步
同步、异步这二者关注的是进程的消息通知机制,即程序运行的方式与结果如何返回。
消息通知:站在调用者角度,发起调用后调用者能不能继续往后走。打个比方吧,不是很准确,但有助理解:
-
同步:必须等待对方返回结果才能继续往后走。
- 假设你去超市买东西,选完商品后,你必须要排队结帐后才能带着商品离开,这就叫同步。
-
异步:无须原地等待,被调用者会通过状态、通知或回调机制等方式通知调用者运行的结果。
- 假设你是富翁,选完商品后让管家去结帐,由管家把商品带回去并告诉你结果,这样你选完商品就可以走了,不用在那里苦苦地排队,这就是异步。
1.2.2、阻塞/非阻塞
主要关注调用者在等待结果返回之前所处的状态,即调用者这段时间该怎么办。
-
阻塞:blocking,调用结果返回之前,调用者被挂起。
- 换成上面的购物例子,就是说你在排队结帐时,在轮到你之前,你什么都不能做,被强制进入冬眠状态。
-
非阻塞:nonblocking,调用结果返回之前,调用者不会被挂起。
- 管家帮你排队结帐,但是时代不一样了,管家直接扫码支付,并让超市送货上门,他也不用在那等了。
根据上面的知识,可以概括出I/O模型一般有同步阻塞、同步非阻塞、异步非阻塞(都异步了,怎么可能会被挂起)。
二、Nginx简述
Nginx是一款免费的、开源的、高性能的(异步非阻塞)HTTP、反向代理、邮件代理、通用TCP/UDP代理(多指负载均衡)服务器,最初由俄罗斯人Igor Sysoev所研发,后来面向全世界开源,由此得到迅速壮大并受到全世界技术人员的喜爱。
Nginx版本有两种,其中奇数版本为开发版本,如1.19;偶数版为稳定版本,如1.20。
三、Nginx程序架构
3.1、程序架构
Nginx由master、worker、cache进程组成:
-
master进程:不负责处理请求,仅负责加载和分析配置文件、管理worker进程、平滑升级;master可以看成是团队的领导,负责成员的管理而不负责具体的工作事务。
-
worker进程:由master进程生成,负责处理各种请求;master进程可以创建多个worker进程,一个worker进程可以处理多个请求;worker就像团队中的成员,负责处理日常工作事务。
-
缓存相关的进程(需要配置后才会启动):
- cache loader:载入缓存对象
- cache manager:管理缓存对象
图片来源于网络
3.2、Nginx特性
Nginx特性有:异步非阻塞、事件驱动、并发请求处理、高度模块化。
3.2.1、Nginx模块
Nginx高度模块化,但其模块早期不支持DSO机制;近期版本支持动态装载和卸载;更多详情请参照Nginx官方文档。
-
核心模块:core module
-
标准模块:
- HTTP modules:
- Standard HTTP modules,标准web模块
- Optional HTTP modules,可选
- Mail modules
- Stream modules:流模块,负责传输层负载均衡、传输层代理等。
- HTTP modules:
-
第三方模块
3.3、Nginx的功用
- 静态的web资源服务器;(图片服务器,或js/css/html/txt等静态资源服务器)
- 结合FastCGI/uwSGI/SCGI等协议反代动态资源请求;
- http/https协议的反向代理;
- imap4/pop3协议的反向代理;
- tcp/udp协议的请求转发;
3.4、Nginx安装
ArchLinux系统安装如下所示,其它平台请自行安装。
sudo pacman -S nginx
3.5、程序环境
配置文件的组成部分:
- 主配置文件:nginx.conf,默认是在/etc/nginx/nginx.conf
- include conf.d/*.conf,在此目录下的以conf结尾的文件都会被识别。
- fastcgi, uwsgi,scgi等协议相关的配置文件
- mime.types:支持的mime类型
- 主程序文件:/usr/sbin/nginx
Unit File:nginx.service - 注意:
- Nginx配置文件中指令必须以分号结尾;
- 支持使用配置变量;
- 内建变量:由Nginx模块引入,可直接引用;
- 自定义变量:由用户使用set命令定义;
- set variable_name value;
- 引用变量:$variable_name
四、Nginx配置文件
4.1、主配置结构
Nginx主配置文件为/etc/nginx/nginx.conf
event {
worker_connections 1024; # 事件驱动相关的配置;
}
http {
...; # http/https协议相关的配置段
}
mail {
...; # 邮件代理相关
}
stream {
...; # 流相关配置
}
3.2、全局配置指令
main配置段常见的配置指令(全局生效):
-
正常运行必备的配置
-
优化性能相关的配置
-
用于调试及定位问题相关的配置
-
事件驱动相关的配置
3.2.1、运行必备配置
user
user后面跟用户名即可,用户组不填则组名默认跟用户同名。
user http;
pid
指定存储nginx主进程进程号码的文件路径
pid /run/nginx.pid;
include
指定导入的其它的配置文件的路径
include /etc/nginx/modules-enabled/*.conf;
3.2.2、性能优化配置
worker_processes
worker_processes number | auto;
,worker进程的数量,通常应该小于或等于当前主机的cpu核心数。
worker_processes auto; # auto代表自动检测当前主机物理CPU核心数
worker_cpu_affinity
worker_cpu_affinity auto [cpumask];
绑定进程到cpu,保证每一次都是同一颗cpu管理该worker。
CPU MASK:
- 00000001:0号CPU
- 00000010:1号CPU
- 以此类推,auto是则自动绑定
worker_cpu_affinity auto;
worker_priority
worker_priority number;
指定worker进程的nice,即worker进程优先级;[-20,20];如果Nginx是当前服务器最重要的进程,则有必要设置优先级,内核会优先调度Nginx。
worker_priority -5;
worker_rlimit_nofile
worker_rlimit_nofile number;
worker进程所能够打开的文件数量上限;最大不能超过cpu和worker连接数的乘数
worker_rlimit_nofile 65535;
3.2.3、调试定位问题
daemon
daemon on|off;
是否以守护进程方式运行Nignx;使用systemd的系统不需要配置这里。
daemon on;
master_process
master_process on|off;
是否以master/worker模型运行nginx;即只运行一个master进程不运行worker进程,通常是Nginx二次开发才可能用到。
master_process off;
error_log
error_log file [level];
错误日志等级及保存位置,比如:info warn error等。
error_log logs/error.log info;
3.2.4、事件驱动配置
包含在events里面的都属于事件驱动配置
events {}
worker_connections
worker_connections number;
每个worker进程最大并发数,最大的就是worker_processes * worker_connections
的乘数。
events { worker_connections 1024;}
use
use method;
指明并发连接请求的处理方法,select或者epoll,select最大仅支持1024,而epoll几乎没限制,默认epoll,所以不用写即可。
events { use epoll;}
accept_mutex
accept_mutex on | off;
处理新的连接请求的方法;on意味着由各worker轮流处理新请求,Off意味着每个新请求的到达都会通知所有的worker进程;也就是互斥锁,1.11.3版本后默认是off。
events { accept_mutex off;}
3.3、HTTP配置
http/https协议相关的配置段,格式如下所示:
http {
... ... # 此处定义的配置为全局server公用
server {
... # 如果与HTTP全局配置段同名,则以局部的为准。
server_name
root
location [OPERATOR] /uri/ {
...
}
}
}
3.3.1、套接字相关配置
server
配置一个虚拟主机
server {
listen 80; # 监听端口
server_name blog.sanxi.info; # 监听地址
root /usr/share/nginx; # 根目录
}
listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]
-
default_server:设定为默认虚拟主机;
-
ssl:限制仅能够通过ssl连接提供服务;
-
backlog=number:后援队列长度;
-
rcvbuf=size:接收缓冲区大小;
-
sndbuf=size:发送缓冲区大小;
tcp_nodelay
tcp_nodelay on | off;
在keepalived模式下的连接是否启用TCP_NODELAY选项;off表示不延迟,仅对长连接有效,默认是on.
tcp_nopush
`tcp_nopush on|off;` 在sendfile模式下,是否启用TCP_CORK选项。
sendfile
sendfile on|off;
是否启用sendfile功能。
3.3.2、路径相关配置
root
root path;
设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径;可用的位置:http, server, location, if in location。
location
location [ = | ~ | ~* | ^~ ] uri { ... }
匹配优先级:= ^~ ~/~* 不带符号,在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置。
- =:对URI做精确匹配;例如:blog.sanxi.info、blog.sanxi.info/archives/3-9--bing-fa-bian-cheng-ji-chu-zhi-shi
- ~:对URI做正则表达式模式匹配,区分字符大小写;
- ~*:对URI做正则表达式模式匹配,不区分字符大小写;
- ^~:对URI的左半部分做匹配检查,不区分字符大小写;
- 不带符号:匹配起始于此uri的所有的url;
location / { root /usr/share/nginx/html; index index.html index.htm; deny 192.168.33.33; # 拒绝访问 allow 192.168.33.35; # 允许访问}
alias
alias path;
定义路径别名,文档映射的另一种机制;仅能用于location上下文;
注意:location中使用root指令和alias指令的意义不同;
- root给定的路径对应于location中的/uri/左侧的/;
- alias给定的路径对应于location中的/uri/右侧的/;
index
index file;
,默认资源,可用位置:http, server, location;
location / { root /usr/share/nginx/html; index index.html index.htm;}
error_page
error_page code ... [=[response]] uri;
为指定的错误状态码显示的资源
error_page 500 502 503 504 /50x.html;
3.3.3、客户端请求相关配置
keepalive_timeout
keepalive_timeout timeout [header_timeout];
设定保持连接的超时时长,0表示禁止长连接;默认为65s。
keepalive_timeout 65;
keepalive_requests
keepalive_requests number;
在一次长连接上所允许请求的资源的最大数量,默认为100;
keepalive_disable
keepalive_disable none | browser ...;
对哪种浏览器禁用长连接
send_timeout
send_timeout time;
向客户端发送响应报文的超时时长;此处,是指两次写操作之间的间隔时长,单位秒。
client_body_buffer_size
client_body_buffer_size size;
用于接收客户端请求报文的body部分的缓冲区大小;默认为16k;超出此大小时,其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置;只有需要用户提交大量信息才需要提交,比如博客网站。
client_body_temp_path
client_body_temp_path path [level1 [level2 [level3]]];
设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量;level是16进制的数字;
client_body_temp_path /var/tmp/client_body 1 2 2 # 1:表示用一位16进制数字表示一级子目录;0-f # 2:表示用2位16进程数字表示二级子目录:00-ff # 2:表示用2位16进程数字表示三级子目录:00-ff
3.3.4、客户端限制相关配置
limit_rate
limit_rate rate;
限制响应给客户端的传输速率,单位是bytes/second,0表示无限制,默认是0。
limit_except
limit_except method ... { ... }
限制对指定的请求方法之外(post,get那些)的其它方法的使用客户端;
limit_except GET { allow 192.168.1.0/24; deny all;}
3.3.5、文件操作优化配置
aio
aio on | off | threads[=pool];
是否启用aio即异步I/O功能;很重要,最好on。
open_file_cache
open_file_cache off;
open_file_cache max=N [inactive=time];
Nginx可以缓存以下三种信息:
- 文件的描述符、文件大小和最近一次的修改时间。
- 打开的目录结构。
- 没有找到的或者没有权限访问的文件的相关信息。
max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现缓存管理;
inactive=time:缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项;
off:禁用缓存
open_file_cache_valid
open_file_cache_valid time;
缓存项有效性的检查频率,默认为60s。
open_file_cache_min_uses
open_file_cache_min_uses number;
在open_file_cache指令的inactive参数指定的时长内,至少应该被命中多少次方可被归类为活动项。
open_file_cache_errors
open_file_cache_errors on | off;
是否缓存查找时发生错误的文件一类的信息
3.3.6、ngx_http_access_module
实现基于ip的访问控制功能,也就是黑白名单,在3.3.4小节有演示,可用位置:http, server, location, limit_except。
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
3.3.7、ngx_http_auth_basic_module
实现基于用户的访问控制,使用basic机制进行用户认证。
auth_basic
auth_basic string | off;
描述文本
auth_basic_user_file
auth_basic_user_file file;
这个文件需要用htpasswd创建,htpasswd命令由httpd-tools所提供htpasswd -c -m /etc/nginx/.ngxpasswd username
htpasswd -m /etc/nginx/.ngxpasswd username
location /admin/ { alias /webapps/app1/data/; auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.ngxpasswd;}
3.3.8、ngx_http_stub_status_module
用于输出nginx的基本状态信息;内嵌状态页
stub_status
location /basic_status { stub_status;}
输出信息如下所示:
Active connections: 291 server accepts handled requests 16630948 16630948 31070465 Reading: 6 Writing: 179 Waiting: 106
- Active connections: 活动状态的连接数;
- accepts:已经接受的客户端请求的总数;
- handled:已经处理完成的客户端请求的总数;
- requests:客户端发来的总的请求数;
- Reading:处于读取客户端请求报文首部的连接的连接数;
- Writing:处于向客户端发送响应报文过程中的连接数;
- Waiting:处于等待客户端发出请求的空闲连接数;
3.3.9、ngx_http_log_module
log_format
定义访问日志的格式
log_format name string ...;
string可以使用nginx核心模块及其它模块内嵌的变量。
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
访问日志配置
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
访问日志文件路径,格式及相关的缓冲的配置;
buffer=size
flush=time
open_log_file_cache
缓存各日志文件相关的元数据信息
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
- max:缓存的最大文件描述符数量;
- min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项;
- inactive:非活动时长;
- valid:验正缓存中各缓存项是否为活动项的时间间隔;
3.3.10、ngx_http_gzip_module
管理响应客户端的报文的压缩功能
gzip on | off;
开启或关闭响应报文压缩功能
gzip_comp_level level;
压缩等级:1 - 9。
gzip_disable regex ...;
禁止“User-Agent”与指定的正则表达式匹配的请求的响应报文进行压缩
gzip_min_length length;
启用压缩功能的响应报文大小阈值
gzip_buffers number size;
支持实现压缩功能时为其配置的缓冲区数量及每个缓存区的大小
gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
nginx作为代理服务器接收到从被代理服务器发送的响应报文后,在何种条件下启用压缩功能的;
off:对代理的请求不启用
no-cache, no-store,private:表示从被代理服务器收到的响应报文首部的Cache-Control的值为此三者中任何一个,则启用压缩功能;
gzip_types mime-type ...;
压缩过滤器,仅对此处设定的MIME类型的内容启用压缩功能
# Gzip Settingsgzip on;gzip_vary on;gzip_proxied any;gzip_comp_level 6;gzip_buffers 16 8k;gzip_http_version 1.1;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
3.3.11、ngx_http_ssl_module
-
ssl on | off;
为指定的虚拟机开启https服务 -
ssl_certificate file;
当前虚拟主机使用PEM格式的证书文件 -
ssl_certificate_key file;
当前虚拟主机上与其证书匹配的私钥文件 -
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
支持的ssl协议版本,默认为后三个; -
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
builtin[:size]
:使用OpenSSL内建的缓存,此缓存为每worker进程私有;[shared:name:size]
:在各worker之间使用一个共享的缓存;
-
ssl_session_timeout time;
客户端一侧的连接可以复用ssl session cache中缓存 的ssl参数的有效时长;server { listen 443 ssl; server_name localhost; ssl_certificate cert.pem; ssl_certificate_key cert.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; }}
3.3.12、ngx_http_rewrite_module
用于重定向,将用户请求的URI基于正则表达式所描述的模式进行检查,而后完成替换。
-
rewrite regex replacement [flag]
将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI;
注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查,因此,隐含有循环机制;[flag]所表示的标志位用于控制此循环机制;- replacement:是以http://或https://开头,则替换结果会直接以重向返回给客户端;301:永久重定向;
- [flag]:
- last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环;
- break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环;
- redirect:重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;不能以http://或https://开头;
- permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;
-
return
- return code [text]; 停止处理并返回特定状态码给客户端
- return code URL; 返回状态码并重定向至指定的url
- return URL; 直接重定向到指定的url
-
rewrite_log on | off;
是否开启重写日志; -
if (condition) { ... }
引入一个新的配置上下文 ;条件满足时,执行配置块中的配置指令;server, location;-
condition:
=
比较操作符:
~:模式匹配,区分字符大小写;
~:模式匹配,不区分字符大小写;
!~:模式不匹配,区分字符大小写;
!~:模式不匹配,不区分字符大小写;
文件及目录存在性判断:
-e, !-e
-f, !-f
-d, !-d
-x, !-x
-
-
set $variable value;
用户自定义变量 ;server { if ($host = blog.sanxi.info) { return 301 https://$host$request_uri; } listen 80; server_name blog.sanxi.info; return 404; # managed by Certbot}
3.3.13、ngx_http_referer_module
用于阻止“Referer”报头字段中包含无效值的请求访问站点。
valid_referers
valid_referers none | blocked | server_names | string ...;
定义referer首部的合法可用值
-
none:请求报文首部没有referer首部;
-
blocked:请求报文的referer首部没有值;
-
server_names:参数,其可以有值作为主机名或主机名模式;
-
arbitrary_string:直接字符串,但可使用作通配符;
-
regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~.*.magedu.com;
valid_referers none block server_names *.sanxi.info;if($invalid_referer) { return http://www.magedu.com/invalid.jpg;}
五、Nginx反向代理
本节主要学习如何使用nginx反向代理各种协议
5.1、ngx_http_proxy_module
用于反向代理请求到其它服务器
proxy_pass URL;
使用位置:location, if in location, limit_except
注意:proxy_pass后面的路径不带uri时,其会将location的uri传递给后端主机;proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri;
如果location定义其uri时使用了正则表达式的模式,或在if语句或limt_execept中使用proxy_pass指令,则proxy_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加代理到的服务的之后。
proxy_set_header
proxy_set_header field value;
设置发往后端主机的请求报文的请求首部的值;使用位置:http, server, location
location / { proxy_set_header HOST $host; # 保持原请求地址 proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8090/; server_tokens off;}
proxy_cache_path
定义可用于proxy功能的缓存;使用位置:http
proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
proxy_cache_path /var/cache/nginx/ levels=1:1:1 keys_zone=pxycache:20m max_size=1g;
proxy_cache
proxy_cache zone | off;
指明要调用的缓存,或关闭缓存机制;使用位置:http, server, location
proxy_cache_key
proxy_cache_key string;
缓存中用于“键”的内容;
默认值:proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid
proxy_cache_valid [code ...] time;
定义对特定响应码的响应内容的缓存时长
定义在需要调用缓存功能的配置段,例如server;
proxy_cache pxycache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 301 1h;
proxy_cache_valid any 1m;
proxy_cache_use_stale
设置发生指定状态码的错误时可以使用过时的缓存
proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...;
proxy_cache_methods
当客户端的请求属于是列表中的方法,则使用缓存响应
proxy_cache_methods GET | HEAD | POST ...;
proxy_connect_timeout
与代理服务器的连接超时时间,默认为60s;最长为75s。
proxy_connect_timeout time;
proxy_read_timeout
从代理服务器获取响应的超时时间,仅在两个连续读取操作之间有效,不影响整个响应的传输。
proxy_read_timeout time;
proxy_send_timeout
从代理服务器获取响应的超时时间,仅在两个连续写入操作之间有效,不影响整个响应的传输。
proxy_send_timeout time;
5.2、ngx_http_headers_module
在代理服务器响应给客户端的响应报文中添加自定义首部,或修改指定首部的值。
add_header
添加自定义首部
add_header name value [always];
- add_header X-Via $server_addr;
add_header X-Accel $server_name;
expires
用于定义Expire或Cache-Control首部的值
expires [modified] time;
expires epoch | max | off;
5.3、ngx_http_fastcgi_module
允许将请求传递到FastCGI服务器
fastcgi_pass
address为fastcgi server的地址;使用位置:location, if in location。
fastcgi_pass address;
fastcgi_index
fastcgi_index name;
fastcgi默认的主页资源;
fastcgi_param
设置应传递给FastCGI服务器的参数,该值可以包含文本、变量及其组合。
fastcgi_param parameter value [if_not_empty];
前提:配置好fpm server和mariadb-server服务
location ~* \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}
配置示例2:通过/pm_status和/ping来获取fpm server状态信息;
location ~* ^/(pm_status|ping)$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;}
fastcgi_cache_path
定义fastcgi的缓存;缓存位置为磁盘上的文件系统,由path所指定路径来定义
fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
- levels=levels:缓存目录的层级数量,以及每一级的目录数量;如:
leves=1:2:2
- keys_zone=name:size,k/v映射的内存空间的名称及大小
- inactive=time,非活动时长
- max_size=size,磁盘上用于缓存数据的缓存空间上限
fastcgi_cache
fastcgi_cache zone | off;
调用指定的缓存空间来缓存数据;http, server, location
fastcgi_cache_key
fastcgi_cache_key string;
定义用作缓存项的key的字符串;
fastcgi_cache_methods
fastcgi_cache_methods GET | HEAD | POST ...;
为哪些请求方法使用缓存;
fastcgi_cache_min_uses
缓存空间中的缓存项在inactive定义的非活动时间内至少要被访问到此处所指定的次数方可被认作活动项
fastcgi_cache_min_uses number;
fastcgi_cache_valid
fastcgi_cache_valid [code ...] time;
不同的响应码各自的缓存时长
http { fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:1 keys_zone=fcgi:20m inactive=120s; server { location ~* \.php$ { fastcgi_cache fcgi; fastcgi_cache_key $request_uri; fastcgi_cache_valid 200 302 10m; fastcgi_cache_valid 301 1h; fastcgi_cache_valid any 1m; } }}
fastcgi_keep_conn
默认情况下,FastCGI服务器将在发送响应后立即关闭连接。但是,当此指令设置为On值时,nginx将指示FastCGI服务器保持连接打开。
fastcgi_keep_conn on | off;
六、Nginx负载均衡
Nginx有ngx_http_upstream_module模块和ngx_stream_upstream_module模块可以实现负载均衡功能。
- ngx_http_upstream_module
- 用于定义可由PROXY_PASS、Fastcgi_PASS、uwsgi_PASS、SCGI_PASS和memcached_PASS指令引用的服务器组。
- ngx_stream_upstream_module
- 1.9.0版本后用于定义可由PROXY_PASS指令引用的服务器组。
upstream httpdsrvs { # httpdsrvs是自定义的组名,可以在反代中直接指向此处负载均衡组名
server 192.168.33.33:80;
server 192.168.33.36:80;
}
ngx_http_upstream_module
-
upstream name { ... }
定义后端服务器组,会引入一个新的上下文;只能在http里用。 -
server address [parameters];
- 在upstream上下文中server成员,以及相关的参数;Context: upstream
- address的表示格式:
- unix:/PATH/TO/SOME_SOCK_FILE,sock套接字。
- IP[:PORT],IP地址+端口
- HOSTNAME[:PORT],主机名+端口
- parameters:
- weight=number,权重,可以理解为优先级,默认为1。
- max_fails=number
- 0则不检测 失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用。
- fail_timeout=time,设置将服务器标记为不可用状态的超时时长。
- max_conns=number,当前的服务器的最大并发连接数。
- backup,将服务器标记为“备用”,即所有服务器均不可用时此服务器才启用。
- down,标记为“不可用”,比如灰度升级时标记它。
-
least_conn;
,最少连接调度算法,当server拥有不同的权重时其为wlc。 -
ip_hash;
,源地址hash调度方法,让一个IP地址始终绑定给同一台server,这个指令没有值,就这么写在第一行 -
hash key [consistent];
,基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者的组合。思考:如何将请求分类,同一类请求将发往同一个upstream server?
hash $request_uri consistent;
这个可以和缓存配合,很好用。hash $remote_addr;
跟上面的ip hash一样绑定同一个地址给同一台server。
-
keepalive connections;
,为每个worker进程保留的空闲的长连接数量,比如每个worker32个。
ngx_stream_core_module
模拟反代基于tcp或udp的服务连接,即工作于传输层的反代或调度器;
stream { ... }
,定义stream相关的服务;Context:main
server {
listen 10.1.0.6:22022;
proxy_pass sshsrvs;
}
stream {
upstream sshsrvs {
server 192.168.22.2:22;
server 192.168.22.3:22;
least_conn;
}
}
Nginx(4)
LB Cluster: 传输层:lvs、nginx、haproxy 应用层:nginx(http, https, smtp, pop, imap), haproxy(http), httpd(http/https), ats, perlbal, pound, ... nginx load balancer: tcp/udpnginx proxy: reverse proxy: 应用程序发布: 灰度模型: (1) 如果存在用户会话; 从服务器上拆除会话; (2) 新版本应用程序存在bug; 回滚; ngx_http_proxy_module (1) proxy_pass URL; location, if in location, limit_except 注意:proxy_pass后面的路径不带uri时,其会将location的uri传递给后端主机; location /uri/ { proxy_pass http://HOST; } proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri; location /uri/ { proxy_pass http://HOST/new_uri/; } 如果location定义其uri时使用正则表达式的模式,则proxy_pass之后必须不能使用uri; location ~|~* PATTERN { proxy_pass http://HOST; } (2) proxy_set_header field value; 设定发往后端主机的请求报文的请求首部的值; 示例: proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for (3) proxy_cache_path proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; (4) proxy_cache zone | off; 调用的缓存的名称,或禁用缓存; (5) proxy_cache_key string; 缓存条目的键; (6) proxy_cache_valid [code ...] time; 对各类响应码的缓存时长; 使用示例: 定义在http{}中: proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:1 keys_zone=pcache:10m max_size=1g; 定义在server{}及其内部的组件中: proxy_cache pcache; proxy_cache_key $request_uri; proxy_cache_valid 200 302 10m; proxy_cache_valid 301 1h; proxy_cache_valid any 1m; (7) proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...; (8) proxy_connect_timeout proxy_read_timeout proxy_send_timeout (9) proxy_buffer_size proxy_buffering proxy_buffers ngx_http_headers_module The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header. (1) add_header name value [always]; 向响应报文中添加自定义首部; 可用上下文:http, server, location, if in location add_header X-Via $server_addr; add_header X-Accel $server_name; (2) expires [modified] time; expires epoch | max | off; 用于定义Expire或Cache-Control首部的值,或添加其它自定义首部;
回顾:
LB Cluster:
传输层:lvs, nginx(stream), haproxy(mode tcp)
应用层:
http/https:nginx(upstream), haproxy(mode http), httpd, ats, perlbal, pound, ...
lvs: 类型:nat/dr/tun/fullnat 算法: 静态:rr, wrr, sh, dh 动态:lc, wlc, sed, nq, lblc, lblcr session保持: session sticky(SourceIP/Cookie) session replication cluster session server(redis/...) Nginx: web:web server, web reverse proxy mail:mail reverse proxy tcp/udp:stream module ngx_http_proxy_module proxy_path proxy_cache_path proxy_cache proxy_cache_key proxy_cache_valid proxy_cache_methods
Nginx(4)
ngx_http_upstream_module The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives. (1) upstream name { ... } 定义后端服务器组;引入一个新的上下文;只能用于http{}上下文中; 默认的调度方法是wrr; (2) server address [parameters]; 定义服务器地址和相关的参数; 地址格式: IP[:PORT] HOSTNAME[:PORT] unix:/PATH/TO/SOME_SOCK_FILE 参数: weight=number 权重,默认为1; max_fails=number 失败尝试的最大次数; fail_timeout=time 设置服务器为不可用状态的超时时长; backup 把服务器标记为“备用”状态; down 手动标记其为不可用; (3) least_conn; 最少连接调度算法; 当server拥有不同的权重时为wlc;当所有后端主机的连接数相同时,则使用wrr进行调度; (4) least_time header | last_byte; 最短平均响应时长和最少连接; header:response_header; last_byte: full_response; 仅Nginx Plus有效; (5) ip_hash; 源地址hash算法;能够将来自同一个源IP地址的请求始终发往同一个upstream server; (6) hash key [consistent]; 基于指定的key的hash表实现请求调度,此处的key可以文本、变量或二者的组合; consistent:参数,指定使用一致性hash算法; 示例: hash $request_uri consistent hash $remote_addr hash $cookie_name (7) keepalive connections; 可使用长连接的连接数量; (8) health_check [parameters]; 定义对后端主机的健康状态检测机制;只能用于location上下文; 可用参数: interval=time:检测频率,默认为每隔5秒钟; fails=number:判断服务器状态转为失败需要检测的次数; passes=number:判断服务器状态转为成功需要检测的次数; uri=uri:判断其健康与否时使用的uri; match=name:基于指定的match来衡量检测结果的成败; port=number:使用独立的端口进行检测; 仅Nginx Plus有效; (9) match name { ... } Defines the named test set used to verify responses to health check requests. 定义衡量某检测结果是否为成功的衡量机制; 专用指令: status:期望的响应码; status CODE status ! CODE ... header:基于响应报文的首部进行判断 header HEADER=VALUE header HEADER ~ VALUE ... body:基于响应报文的内容进行判断 body ~ "PATTERN" body !~ "PATTERN" 仅Nginx Plus有效; 博客作业:以上所有内容;课外实践:实践tengine和Openresty; ngx_stream_core_module The ngx_stream_core_module module is available since version 1.9.0. This module is not built by default, it should be enabled with the --with-stream configuration parameter. (1) listen address:port [ssl] [udp] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]]; 监听的端口; 默认为tcp协议; udp: 监听udp协议的端口; ngx_stream_proxy_module The ngx_stream_proxy_module module (1.9.0) allows proxying data streams over TCP, UDP (1.9.13), and UNIX-domain sockets. (1) proxy_pass address; Sets the address of a proxied server. The address can be specified as a domain name or IP address, and a port or as a UNIX-domain socket path. (2) proxy_timeout timeout; Sets the timeout between two successive read or write operations on client or proxied server connections. If no data is transmitted within this time, the connection is closed. 默认为10m; (3) proxy_connect_timeout time; Defines a timeout for establishing a connection with a proxied server. 设置nginx与被代理的服务器尝试建立连接的超时时长;默认为60s;
示例:
stream {
upstream sshsrvs {
server 192.168.10.130:22;
server 192.168.10.131:22;
hash $remote_addr consistent;
}
server {
listen 172.16.100.6:22202;
proxy_pass sshsrvs;
proxy_timeout 60s;
proxy_connect_timeout 10s;
}
}
编译安装:
前提:开发环境,包括nginx编译要启用的功能依赖到的开发库;
# yum groupinstall "Development Tools" "Server Platform Development"
# yum -y pcre-devel openssl-devel
编译过程:
# ./configure --prefix=/usr/local/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_flv_module --with-http_mp4_module --with-threads --with-file-aio
# make && make install
课程实践:
nginx--> AMPs(wordpress)
nginx--> FPMs(wordpress)
nginx--> images servers ( imgs.magedu.com)
location ~* .(jpg|png|gif|jpeg)$ {
...
}
dynamic content servers (shop.magedu.com)
location ~* .php$ {
...
}
location / {
...
}
自定义错误404和5xx错误页,文本静态内容传输压缩;