title=

本章内容

Nginx介绍

Nginx安装


Nginx各种模块

实验:实现LNMP

性能影响

有很多研究都表明,性能对用户的行为有很大的影响:

79%的用户表示不太可能再次打开一个缓慢的网站

47%的用户期望网页能在2秒钟以内加载

40%的用户表示如果加载时间超过三秒钟,就会放弃这个网站

页面加载时间延迟一秒可能导致转换损失7%,页面浏览量减少11%

8秒定律:用户访问一个网站时,如果等待网页打开的时间超过8秒,会有超过30%的用户放弃等待

用户速度体验的1-3-10原则:

 title=

Httpd MPM

httpd MPM:

prefork:进程模型,两级结构,主进程master负责生成子进程,每个子进程负责响应一个请求

worker:线程模型,三级结构,主进程master负责生成子进程,每个子进程负责生成多个线程,每个线程响应一个请求

event:线程模型,三级结构,主进程master负责生成子进程,每个子进程响应多个请求

Nginx介绍

Nginx:engine X ,2002年,开源,商业版

NGINX是免费,开源,高性能的HTTP和反向代理服务器,邮件代理服务器,通用TCP/UDP代理服务器

解决C10K问题(10K Connections)

官网:http://nginx.org

二次开发版:

Tengine, OpenResty(章亦春)

正向代理和反向代理

 title=

Nginx介绍

特性:

模块化设计,较好的扩展性

高可靠性

支持热部署:不停机更新配置文件,升级版本,更换日志文件

低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存

event-driven,aio,mmap,sendfile

基本功能:

静态资源的web服务器 #重点掌握

http协议反向代理服务器 #重点掌握

pop3/imap4协议反向代理服务器

FastCGI(LNMP),uWSGI(python)等协议

模块化(非DSO),如zip,SSL模块

nginx的程序架构

web服务相关的功能:

虚拟主机(server)

支持 keep-alive 和管道连接

访问日志(支持基于日志缓冲提高其性能)

url rewrite

路径别名

基于IP及用户的访问控制

支持速率限制及并发数限制

重新配置和在线升级而无须中断客户的工作进程

Memcached 的 GET 接口

nginx架构

 title=

nginx支持epoll,apache使用select

nginx的程序架构

nginx的程序架构:

master/worker结构

一个master进程:

负载加载和分析配置文件、管理worker进程、平滑升级

一个或多个worker进程

处理并响应用户请求

缓存相关的进程:

cache loader:载入缓存对象

cache manager:管理缓存对象

nginx模块

nginx高度模块化,但其模块早期不支持DSO机制;1.9.11版本之后支持动态装载和卸载

模块分类:

核心模块:core module

标准模块:

•HTTP 模块: ngx\_http\_*

HTTP Core modules 默认功能

HTTP Optional modules 需编译时指定

•Mail 模块 ngx\_mail\_*

•Stream 模块 ngx\_stream\_*

第三方模块

nginx的功用

静态的web资源服务器

html,图片,js,css,txt等静态资源

结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求

http/https协议的反向代理

imap4/pop3协议的反向代理

tcp/udp协议的请求转发(反向代理)

nginx的安装

官方:

http://nginx.org/packages/centos/7/x86\_64/RPMS

Fedora-EPEL:

https://mirrors.aliyun.com/epel/7/x86\_64/

编译安装:

•yum install pcre-devel openssl-devel zlib-devel

•useradd -r nginx

•./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http\_ssl\_module --with-http\_v2\_module --with-http\_dav\_module --with-http\_stub\_status\_module --with-threads --with-file-aio

•make && make install

ningx源码

可更改编译安装后的nginx的名称和版本

./src/http/ngx\_http\_header\_filter\_module.c 第49行左右:改软件名 "Server:nginx" CRLF; 安装后会显示在加了server\_tokens后的隐藏的nginx版本

./src/core/nginx.h 第13和14行左右:版本号和软件名:#define NGINX\_VERSION和 #define NGINX\_VER,安装后会显示在没加server\_tokens的时候的nginx版本号和名称

编译安装nginx选项

编译安装nginx选项:

--prefix=/etc/nginx 安装路径

--sbin-path=/usr/sbin/nginx 指明nginx程序文件安装路径

--conf-path=/etc/nginx/nginx.conf 主配置文件安装位置

--error-log-path=/var/log/nginx/error.log 错误日志文件安装位置

--http-log-path=/var/log/nginx/access.log 访问日志文件安装位置

--pid-path=/var/run/nginx.pid 指明pid文件安装位置

--lock-path=/var/run/nginx.lock 锁文件安装位置

--http-client-body-temp-path=/var/cache/nginx/client\_temp 客户端body部分的临时文件存放路径,服务器允许客户端使用put方法提交大数据时,临时存放的磁盘路径

--http-proxy-temp-path=/var/cache/nginx/proxy\_temp 作为代理服务器,服务器响应报文的临时文件存放路径

--http-fastcgi-temp-path=/var/cache/nginx/fastcgi\_temp 作为fastcgi代理服务器,服务器响应报文的临时文件存放路径

--http-uwsgi-temp-path=/var/cache/nginx/uwsgi\_temp 作为uwsgi代理服务器,服务器响应报文的临时文件存放路径

--http-scgi-temp-path=/var/cache/nginx/scgi\_temp 作为scgi反代服务器,服务器响应报文的临时文件存放路径

--user=nginx 指明以那个身份运行worker进程,主控master进程一般由root运行

--group=nginx

--with-http\_ssl\_module 表示把指定模块编译进来

nginx目录结构和命令

ls /usr/local/nginx/

html是测试页,sbin是主程序

ls /usr/local/nginx/sbin/

nginx 只有一个程序文件

ls /usr/local/nginx/html/

50x.html index.html 测试网页

Nginx:默认为启动nginx

-h 查看帮助选项

-V 查看版本和配置选项(可看到TLS SNI support enabled,这个很有用,可在一台机上搭建多个https主机,而apache做不到)

-t 测试nginx语法错误

-c filename 指定配置文件(default: /etc/nginx/nginx.conf)

-s signal 发送信号给master进程,signal可为:stop, quit, reopen, reload

示例: nginx -s stop 停止

nginx -s reload 加载配置文件(实际中有时用这个,可不用systemd管理)

-g directives 在命令行中指明全局指令

nginx配置

官方文档:https://nginx.org/en/docs[/variables]…

配置文件的组成部分:

主配置文件:nginx.conf

子配置文件 include conf.d/*.conf

fastcgi, uwsgi,scgi等协议相关的配置文件

mime.types:支持的mime类型

主配置文件的配置指令:

directive value [value2 ...];

注意:

(1) 指令必须以分号结尾

(2) 支持使用配置变量

内建变量:由Nginx模块引入,可直接引用

自定义变量:由用户使用set命令定义

set variable\_name value;

引用变量:$variable\_name

nginx配置文件

主配置文件结构:四部

main block:主配置段,即全局配置段,对http,mail都有效

event {

...

} 事件驱动相关的配置

http {

...

} http/https 协议相关配置段

mail {

...

} mail 协议相关配置段

stream {

...

} stream 服务器相关配置段

http协议相关的配置结构

http {

...

... 各server的公共配置

server { 每个server用于定义一个虚拟主机

...

}

server {

...

server\_name 虚拟主机名

root 主目录

alias 路径别名

location [OPERATOR] URL { 指定URL的特性

...

if CONDITION {

...

}

}

}

}

nginx配置

Main 全局配置段常见的配置指令分类

正常运行必备的配置

优化性能相关的配置

用于调试及定位问题相关的配置

事件驱动相关的配置

帮助文档

http://nginx.org/en/docs/

正常运行必备的配置:

帮助文档:http://nginx.org/en/docs/ngx\_core\_module.html

1、user

Syntax: user user [group];

Default: user nobody nobody;

Context: main(只能放在main语句块里)

指定worker进程的运行身份,如组不指定,默认和用户名同名

2、pid /PATH/TO/PID\_FILE

指定存储nginx主进程PID的文件路径

3、include file | mask

指明包含进来的其它配置文件片断

4、load\_module file

模块加载配置文件:/usr/share/nginx/modules/*.conf

指明要装载的动态模块路径: /usr/lib64/nginx/modules

性能优化相关的配置:

1、worker\_processes number | auto

worker进程的数量;auto通常应该为当前主机的cpu的物理核心数

2、worker\_cpu\_affinity cpumask ...

worker\_cpu\_affinity auto [cpumask] 提高缓存命中率

CPU MASK:00000001:0号CPU

00000010:1号CPU

10000000:8号CPU

worker\_cpu\_affinity 0001 0010 0100 1000;

worker\_cpu\_affinity 0101 1010;

px axo pid,cmd,psr | grep nginx查看worker进程工作在哪颗CPU上

3、worker\_priority number

指定worker进程的nice值,设定worker进程优先级:[-20,20]

4、worker\_rlimit\_nofile number

worker进程所能够打开的文件数量上限,如65535(所有worker的总值,也是总最大并发连接数量上限,可调大)

事件驱动相关的配置:

events {

...

}

1、worker\_connections number

每个worker进程所能够打开的最大并发连接数数量,如10240(跟worker\_rlimit\_nofile number相乘即为总最大并发连接数)

总最大并发数:worker\_processes(worker进程数) * worker\_connections

可以设定worker\_rlimit\_nofile等于总最大并发数

2、use method

指明并发连接请求的处理方法 ,默认自动选择最优方法

use epoll;

3、accept\_mutex on | off 互斥

处理新的连接请求的方法;on指由各个worker轮流处理新请求,Off指每个新请求的到达都会通知(唤醒)所有的worker进程,但只有一个进程可获得连接,造成“惊群”,影响性能,最好设成On

调试和定位问题:

1、daemon on|off

是否以守护进程方式运行nignx,默认是守护进程方式(如果变成off则为前台执行,经常改配置测试时可用,Ctrl+C即可停止,nginx即可开始,操作方便)

2、master\_process on|off

是否以master/worker模型运行nginx;默认为on

off 将不启动worker

3、error\_log file [level]

错误日志文件及其级别;出于调试需要,可设定为debug;但debug仅在编译时使用了“--with-debug”选项时才有效

方式:file /path/logfile;

stderr:发送到标准错误

syslog:server-address[,parameter=values]:发送到syslog memory:size 内存

level:debug|info|notice|warn|error|crit|alter|emerg

http协议的相关配置:

http {

... ...

server {

...

server\_name

root

location [OPERATOR] /uri/ {

...

}

}

server {

...

}

}

ngx\_http\_core\_module

与套接字相关的配置:

1、server { ... }

配置一个虚拟主机

server {

listen address[:PORT]|PORT;

server\_name SERVER\_NAME;

root /PATH/TO/DOCUMENT\_ROOT;

}

2、listen PORT|address[:port]|unix:/PATH/TO/SOCKET\_FILE

listen address[:port] [default\_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]

default\_server 设定为默认虚拟主机

ssl 限制仅能够通过ssl连接提供服务

backlog=number 超过并发连接数后,新请求进入后援队列的长度

rcvbuf=size 接收缓冲区大小

sndbuf=size 发送缓冲区大小

注意:

(1) 基于port;

listen PORT; 指令监听在不同的端口

(2) 基于ip的虚拟主机

listen IP:PORT; IP 地址不同

(3) 基于hostname

server\_name fqdn; 指令指向不同的主机名

3、server\_name name ...;

虚拟主机的主机名称后可跟多个由空白字符分隔的字符串

支持*通配任意长度的任意字符

server\_name *.wind.com www.wind.*

支持~起始的字符做正则表达式模式匹配,性能原因慎用

server\_name ~^www\d+\.wind\.com$

说明:\d 表示 [0-9]

匹配优先级机制从高到低:

(1) 首先是字符串精确匹配 如:www.wind.com

(2) 左侧*通配符 如:*.wind.com

(3) 右侧*通配符 如:www.wind.*

(4) 正则表达式 如: ~^.*\.wind\.com$

(5) default\_server

4、tcp\_nodelay on | off;

在keepalived模式下的连接是否启用TCP\_NODELAY选项

当为off时,延迟发送,合并多个请求后再发送

默认On时,不延迟发送

可用于:http, server, location

5、sendfile on | off;

是否启用sendfile功能,在内核中封装报文直接发送

默认Off

6、server\_tokens on | off | build | string

是否在响应报文的Server首部显示nginx版本(建议设为off,商业版可以指定为任意string,或者改源码也可以)

定义路径相关的配置

7、root

设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径,可用于http, server, location, if in location

server {

...

root /data/www/vhosts;

}

示例

http://www.wind.com/images/logo.jpg

--> /data/www/vhosts/images/logo.jpg

8、location [ = | ~ | ~* | ^~ ] uri { ... }

location @name { ... }

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置

示例:

server {...

server\_name www.wind.com;

location /images/ {

root /data/imgs/; #location中的root根优先级高一点

}

}

http://www.wind.com/images/logo.jpg

--> /data/imgs/images/logo.jpg

=:对URI做精确匹配;

location = / {

...

}

http://www.wind.com/ 匹配

http://www.wind.com/index.html 不匹配

^~:对URI的最左边部分做匹配检查,不区分字符大小写

~:对URI做正则表达式模式匹配,区分字符大小写

~*:对URI做正则表达式模式匹配,不区分字符大小写

不带符号:匹配起始于此uri的所有的uri

匹配优先级从高到低:

=, ^~, ~/~*, 不带符号

示例:

root /vhosts/www/htdocs/

http://www.wind.com/index.html

--> /vhosts/www/htdocs/index.html

server {

root /vhosts/www/htdocs/

location /admin/ {

root /webapps/app1/data/

}

}

http://www.wind.com/admin/index.html

--> /webapps/app1/data/admin/index.html

location示例

location = / {

[ configuration A ]

}

http://www.wind.com/

location / {

[ configuration B ]

}

http://www.wind.com/index.html

location /documents/ {

[ configuration C ]

}

http://www.wind.com/documents/linux.txt

location ^~ /images/ {

[ configuration D ]

}

lhttp://www.wind.com/images/logo.jpeg

location ~* \.(gif|jpg|jpeg)$ {

[ configuration E ]

}

http://www.wind.com/documents/logo.jpg

9、alias path;

路径别名,文档映射的另一种机制;仅能用于location上下文

示例:

http://www.wind.com/bbs/index.php

location /bbs/ {

alias /web/forum/;

} --> /web/forum/index.html

location /bbs/ {

root /web/forum/;

} --> /web/forum/bbs/index.html

注意:location中使用root指令和alias指令的意义不同

(a) root,给定的路径对应于location中的/uri/左侧的/

(b) alias,给定的路径对应于location中的/uri/右侧的/

10、index file ...;

指定默认网页文件,注意:ngx\_http\_index\_module模块

11、error\_page code ... [=[response]] uri;

模块:ngx\_http\_core\_module

定义错误页,以指定的响应状态码进行响应

可用位置:http, server, location, if in location

error\_page 404 /404.html

error\_page 404 =200 /404.html #404响应码改为200或302等,防止某些浏览器劫持,再加个location

location /404[.html] {

root /data/sitea/error/;

}

echo '

FBI WARNING!

' > /data/sitea/error/404.html

 title=

12、try\_files file ... uri;

try\_files file ... =code;

按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误

location /images/ {

try\_files $uri /images/default.gif;

}

location / {

try\_files $uri $uri/index.html $uri.html =404;

}

定义客户端请求的相关配置

13、keepalive\_timeout timeout [header\_timeout];

设定保持连接超时时长,0表示禁止长连接,默认为75s

生产中75s有点太长了,可调短

14、keepalive\_requests number;

在一次长连接上所允许请求的资源的最大数量

默认为100

15、keepalive\_disable none | browser ...

对哪种浏览器禁用长连接

16、send\_timeout time;

向客户端发送响应报文的超时时长,此处是指两次写操作之间的间隔时长,而非整个响应过程的传输时长

17、client\_body\_buffer\_size size;

用于接收每个客户端请求报文的body部分的缓冲区大小;默认为16k;超出此大小时,其将被暂存到磁盘上的由下面client\_body\_temp\_path指令所定义的位置

18、client\_body\_temp\_path path [level1 [level2 [level3]]];

设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量

目录名为16进制的数字;

client\_body\_temp\_path /var/tmp/client\_body 1 2 2

1 1级目录占1位16进制,即2^4=16个目录 0-f

2 2级目录占2位16进制,即2^8=256个目录 00-ff

2 3级目录占2位16进制,即2^8=256个目录 00-ff

例:

client\_body\_temp\_path /var/tmp/client\_body 1 2 2

[root@centos ~]#sha1sum anaconda-ks.cfg

52be534d26c21c12ffcab497533e918e9d0a5658 anaconda-ks.cfg

则anaconda-sk.cfg文件上传后会被存在client\_body\_temp\_path/8/65/a5目录中

因为如果文件数量很多,1亿个文件,都放一个目录的话,查询效率会很低,系统以哈希值来区分,进3个目录,每个目录存的文件就只有100个了,查询效率会变高

对客户端进行限制的相关配置

19、limit\_rate rate;

限制响应给客户端的传输速率,单位是bytes/second

默认值0表示无限制

20、limit\_except method ... { ... },仅用于location

限制客户端使用除了指定的请求方法之外的其它方法

method:GET, HEAD, POST, PUT, DELETE

MKCOL, COPY, MOVE, OPTIONS, PROPFIND,

PROPPATCH, LOCK, UNLOCK, PATCH

limit\_except GET {

allow 192.168.1.0/24;

deny all;

} 除了GET和HEAD 之外其它方法仅允许192.168.1.0/24网段主机使用

GET包含HEAD

文件操作优化的配置

21、aio on | off | threads[=pool];

是否启用aio功能

22、directio size | off;

当文件大于等于给定大小时,例如directio 4m,同步(直接)写磁盘,而非写缓存

23、open\_file\_cache off;

open\_file\_cache max=N [inactive=time];

nginx可以缓存以下三种信息:

(1) 文件元数据:文件的描述符、文件大小和最近一次的修改时间

(2) 打开的目录结构

(3) 没有找到的或者没有权限访问的文件的相关信息

max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现管理

inactive=time:缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open\_file\_cache\_min\_uses指令所指定的次数的缓存项即为非活动项,将被删除

24、open\_file\_cache\_errors on | off;

是否缓存查找时发生错误的文件一类的信息

默认值为off

25、open\_file\_cache\_min\_uses number;

open\_file\_cache指令的inactive参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项

默认值为1

26、open\_file\_cache\_valid time;

缓存项有效性的检查频率

默认值为60s

ngx\_http\_access\_module

ngx\_http\_access\_module模块

实现基于ip的访问控制功能

1、allow address | CIDR | unix: | all;

2、deny address | CIDR | unix: | all;

http, server, location, limit\_except

自上而下检查,一旦匹配,将生效,所以要将条件范围小的置前

示例:

location / {

deny 192.168.1.1;

allow 192.168.1.0/24;

allow 10.1.1.0/16;

allow 2001:0db8::/32;

deny all;

}

ngx\_http\_auth\_basic\_module

ngx\_http\_auth\_basic\_module模块

实现基于用户的访问控制,使用basic机制进行用户认证

1、auth\_basic string | off;

2、auth\_basic\_user\_file file;

location /admin/ {

auth\_basic "Admin Area";

auth\_basic\_user\_file /etc/nginx/.ngxpasswd;

}

用户口令文件:

1、明文文本:格式name:password:comment

2、加密文本:由htpasswd命令实现

httpd-tools所提供

ngx\_http\_stub\_status\_module

ngx\_http\_stub\_status\_module模块

用于输出nginx的基本状态信息

输出信息示例:

Active connections: 291

server accepts handled requests

16630948 16630948 31070465

上面三个数字分别对应accepts,handled,requests三个值

Reading: 6 Writing: 179 Waiting: 106

Active connections:当前状态,活动状态的连接数

accepts:统计总值,已经接受的客户端请求的总数

handled:统计总值,已经处理完成的客户端请求的总数

requests:统计总值,客户端发来的总的请求数

Reading:当前状态,正在读取客户端请求报文首部的连接的连接数

Writing:当前状态,正在向客户端发送响应报文过程中的连接数

Waiting:当前状态,正在等待客户端发出请求的空闲连接数

1、stub\_status;

示例:

location /status {

stub\_status;

allow 172.16.0.0/16;

deny all;

}

ngx\_http\_log\_module

ngx\_http\_log\_module模块

指定日志格式记录请求

1、log\_format name string ...;

string可以使用nginx核心模块及其它模块内嵌的变量

2、access\_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

access\_log off;

访问日志文件路径,格式及相关的缓冲的配置

buffer=size

flush=time

示例

log\_format compression '$remote\_addr-$remote\_user [$time\_local] '

'"$request" $status $bytes\_sent '

'"$http\_referer" "$http\_user\_agent" "$gzip\_ratio"';

access\_log /spool/logs/nginx-access.log compression buffer=32k;

3、open\_log\_file\_cache max=N [inactive=time] [min\_uses=N] [valid=time];

open\_log\_file\_cache off;

缓存各日志文件相关的元数据信息

max:缓存的最大文件描述符数量

min\_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项

inactive:非活动时长

valid:验证缓存中各缓存项是否为活动项的时间间隔

ngx\_http\_gzip\_module

ngx\_http\_gzip\_module

用gzip方法压缩响应数据,节约带宽

1、gzip on | off;

启用或禁用gzip压缩

2、gzip\_comp\_level level;

压缩比由低到高:1 到 9

默认:1

3、gzip\_disable regex ...;

匹配到客户端浏览器不执行压缩

4、gzip\_min\_length length;

启用压缩功能的响应报文大小阈值

5、gzip\_http\_version 1.0 | 1.1;

设定启用压缩功能时,协议的最小版本

默认:1.1

6、gzip\_buffers number size;

支持实现压缩功能时缓冲区数量及每个缓存区的大小

默认:32 4k 或 16 8k

7、gzip\_types mime-type ...;

指明仅对哪些类型的资源执行压缩操作;即压缩过滤器

默认包含有text/html,不用显示指定,否则出错

8、gzip\_vary on | off;

如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”

9、gzip\_proxied off | expired | no-cache | no-store | private | no\_last\_modified | no\_etag | auth | any ...;

nginx充当代理服务器时,对于后端服务器的响应报文,在何种条件下启用压缩功能

off:不启用压缩

expired,no-cache, no-store,private:对后端服务器的响应报文首部Cache-Control值任何一个,启用压缩功能

示例:

gzip on;

gzip\_comp\_level 6;

gzip\_min\_length 64;

gzip\_proxied any;

gzip\_types text/xml text/css application/javascript;

ngx\_http\_ssl\_module

ngx\_http\_ssl\_module模块:

1、ssl on | off;

为指定虚拟机启用HTTPS protocol, 建议用listen指令代替

2、ssl\_certificate file;

当前虚拟主机使用PEM格式的证书文件

3、ssl\_certificate\_key file;

当前虚拟主机上与其证书匹配的私钥文件

4、ssl\_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 支持ssl协议版本,默认为后三个

5、ssl\_session\_cache off | none | [builtin[:size]] [shared:name:size];

none: 通知客户端支持ssl session cache,但实际不支持

builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有

[shared:name:size]:在各worker之间使用一个共享的缓存

6、ssl\_session\_timeout time;

客户端连接可以复用ssl session cache中缓存的ssl参数的有效时长,默认5m

示例:

server {

listen 443 ssl;

server\_name www.wind.com;

root /vhosts/ssl/htdocs;

ssl on;

ssl\_certificate /etc/nginx/ssl/nginx.crt;

ssl\_certificate\_key /etc/nginx/ssl/nginx.key;

ssl\_session\_cache shared:sslcache:20m;

ssl\_session\_timeout 10m;

}

ngx\_http\_rewrite\_module(用得很多)

ngx\_http\_rewrite\_module模块:

将用户请求的URI基于PCRE regex所描述的模式进行检查,而后完成重定向替换

示例:

http://www.wind.com/hn --> http://www.wind.com/henan

http://www.wind.com --> https://www.wind.com/

1、rewrite regex replacement [flag]

将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI

注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查

隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制

如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端, 即永久重定向301

[flag]:

last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环,不建议在location中使用(类似shell脚本中的continue)

break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用(类似shell脚本中的break)

redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302

permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求,状态码:301

2、return

return code [text];

return code URL;

例:return 301 http://www.baidu.com/ 注:code须是301,302,303,307或308才能跳转,详见官方文档

return URL;

停止处理,并返回给客户端指定的响应码

3、rewrite\_log on | off;

是否开启重写日志, 发送至error\_log(notice level)

4、set $variable value;

用户自定义变量

注意:变量定义和调用都要以$开头

5、if (condition) { ... }

条件满足时,执行配置块中的配置指令;server, location

condition:

比较操作符:

= 相同 != 不同

~:模式匹配,区分字符大小写

~*:模式匹配,不区分字符大小写

!~:模式不匹配,区分字符大小写

!~*:模式不匹配,不区分字符大小写

文件及目录存在性判断:

-e, !-e 存在(包括文件,目录,软链接)

-f, !-f 文件 -d, !-d 目录 -x, !-x 执行

例:

www.a.com/images/a.jpg --> www.a.com/media/images/a.jpg

rewrite ^(images/.*)$ /media/$1

www.a.com/bbs/ --> www.a.com/forum

rewrite ^/bbs/(.*)$ /forum/$1 last|redirect|permanent;

实验:httphttps跳转

方法1:

server {

listen 80 default\_server;

server\_name www.a.com;

root /data/sitea/;

location / {

rewrite / https://www.a.com/ redirect;

}

}

server {

listen 443 ssl;

server\_name www.a.com;

root /data/siteassl/;

ssl\_certificate /etc/nginx/conf.d/vhosts/a.crt;

ssl\_certificate\_key /etc/nginx/conf.d/vhosts/a.key;

}

方法2:

server {

listen 80 default\_server;

listen 443 ssl ;

server\_name www.a.com;

root /data/sitea/;

ssl\_certificate /etc/nginx/conf.d/a.crt;

ssl\_certificate\_key /etc/nginx/conf.d/a.key;

ssl\_session\_cache shared:sslcache:20m;

ssl\_session\_timeout 10m;

location / {

if ( $scheme = http ) {

rewrite / https://www.a.com/ redirect;

}

}

}

ngx\_http\_referer\_module(用得多)

ngx\_http\_referer\_module模块:

用来阻止Referer首部无有效值的请求访问,可防止盗链

1、valid\_referers none|blocked|server\_names|string ...;

定义referer首部的合法可用值,不能匹配的将是非法值

none:请求报文首部没有referer首部

blocked:请求报文有referer首部,但无有效值

server\_names:参数,其可以有值作为主机名或主机名模式

arbitrary\_string:任意字符串,但可使用*作通配符

regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,例如: ~.*\.wind\.com

示例1:

valid\_referers none block server\_names *.wind.com wind.* ~\.wind\. ~\.baidu\. ~\.google\.;

if ($invalid\_referer) {

return 403 http://www.wind.com;

}

示例2:

http://www.a.com/daolian.php上有一段盗链代码:

 title=

盗链了http://www.b.com下的sky.jpg这张图片,效果如图:

 title=

现在在http://www.b.com/上加上了一串防盗链代码:

valid\_referers none block server\_names *.b.com b.* ~\.b\.

~\.baidu\. ~\.google\.;

if ($invalid\_referer) {

return 403 ;

}

 title=

加上之后,http://www.a.com/无法盗链了,效果如图:

 title=

ngx\_http\_proxy\_module

ngx\_http\_proxy\_module模块:

转发请求至另一台主机

1、proxy\_pass URL;

Context:location, if in location, limit\_except

注意:proxy\_pass后面路径不带uri时,会将location的uri传递(附加)给后端主机

server {

...

server\_name HOSTNAME;

location /uri/ {

proxy\_pass http://host[:port]; 最后没有/

}

...

}

上面示例:http://HOSTNAME/uri --> http://host/uri

如果上面示例中有 /,即:http://host[:port]/

意味着:http://HOSTNAME/uri --> http://host/ 即置换

proxy\_pass后面的路径是一个uri时,其会将location的uri替换为proxy\_pass的uri

server {

...

server\_name HOSTNAME;

location /uri/ {

proxy\_pass http://host/new\_uri/;

}

...

}

http://HOSTNAME/uri/ --> http://host/new\_uri/

如果location定义其uri时使用了正则表达式的模式,则proxy\_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加至后端服务器之后

server {

...

server\_name HOSTNAME;

location ~|~* /uri/ {

proxy\_pass http://host; 不能加/

}

...

}

http://HOSTNAME/uri/ --> http://host/uri/

2、proxy\_set\_header field value;

设定发往后端主机的请求报文的请求首部的值

Context: http, server, location

proxy\_set\_header X-Real-IP $remote\_addr;

proxy\_set\_header X-Forwarded-For $proxy\_add\_x\_forwarded\_for; #用以多层代理的时候,把中间的代理服务器全加进去,以逗号隔开

请求报文的标准格式如下:

X-Forwarded-For: client1, proxy1, proxy2

后端服务器httpd.conf也要配一下:

\# LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined 把原来这行复制然后注释掉,%h改成%{X-Forwarded-for}i

LogFormat "%{X-Forwarded-for}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

3、proxy\_cache\_path;

定义可用于proxy功能的缓存;Context: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];

4、proxy\_cache zone | off; 默认off

指明调用的缓存,或关闭缓存机制;Context:http, server, location

5、proxy\_cache\_key string;

缓存中用于“键”的内容

默认值:proxy\_cache\_key $scheme$proxy\_host$request\_uri;

6、proxy\_cache\_valid [code ...] time;

定义对特定响应码的响应内容的缓存时长

定义在http{...}中

示例:

proxy\_cache\_valid 200 302 10m;

proxy\_cache\_valid 404 1m;

示例:在http配置定义缓存信息

proxy\_cache\_path /var/cache/nginx/proxy\_cache

levels=1:1:1 keys\_zone=proxycache:20m

inactive=120s max\_size=1g;

说明:proxycache:20m 指内存中缓存的大小,主要用于存放key(如:url)和metadata(如:使用次数,在磁盘中的路径)

max\_size=1g 指磁盘存入文件内容的缓存空间最大值

调用缓存功能,需要定义在相应的配置段,如server{...};

proxy\_cache proxycache;

proxy\_cache\_key $request\_uri;

proxy\_cache\_valid 200 302 301 1h;

proxy\_cache\_valid any 1m;

7、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 ...

在被代理的后端服务器出现哪种情况下,可以真接使用过期的缓存响应客户端

8、proxy\_cache\_methods GET | HEAD | POST ...;

对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

9、proxy\_hide\_header field;

默认nginx在响应报文不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel-等,用于隐藏后端服务器特定的响应首部

10、proxy\_connect\_timeout time;

定义与后端服务器建立连接的超时时长,如超时会出现502错误,默认为60s,一般不建议超出75s

11、proxy\_send\_timeout time;

将请求发送给后端服务器的超时时长;默认为60s

12、proxy\_read\_timeout time;

等待后端服务器发送响应报文的超时时长,默认为60s

ngx\_http\_headers\_module模块

ngx\_http\_headers\_module模块

向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值

1、add\_header name value [always];

添加自定义首部

add\_header X-Via $server\_addr;

add\_header X-Cache $upstream\_cache\_status;

add\_header X-Accel $server\_name;

2、add\_trailer name value [always];

添加自定义响应信息的尾部

ngx\_http\_fastcgi\_module

ngx\_http\_fastcgi\_module模块

转发请求到FastCGI服务器,不支持php模块方式

1、fastcgi\_pass address;

address为后端的fastcgi server的地址

可用位置:location, if in location

2、fastcgi\_index name;

fastcgi默认的主页资源

示例:fastcgi\_index index.php;

3、fastcgi\_param parameter value [if\_not\_empty];

设置传递给 FastCGI服务器的参数值,可以是文本,变量或组合

示例1:

1)在后端服务器先配置fpm server和mariadb-server

2)在前端nginx服务上做以下配置:

location ~* \.php$ {

fastcgi\_pass 后端fpm服务器IP:9000;

fastcgi\_index index.php;

fastcgi\_param SCRIPT\_FILENAME /usr/share/nginx/html$fastcgi\_script\_name; #后端fpm服务器的php脚本目录,这项很重要

include fastcgi\_params;

}

示例2:通过/pm\_status和/ping来获取fpm server状态信息

location ~* ^/(pm\_status|ping)$ {

include fastcgi\_params;

fastcgi\_pass 后端fpm服务器IP:9000;

fastcgi\_param SCRIPT\_FILENAME $fastcgi\_script\_name;

}

4、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];

定义fastcgi的缓存;

path 缓存位置为磁盘上的文件系统

max\_size=size

磁盘path路径中用于缓存数据的缓存空间上限

levels=levels:缓存目录的层级数量,以及每一级的目录数量

levels=ONE:TWO:THREE

示例:leves=1:2:2

keys\_zone=name:size

k/v映射的内存空间的名称及大小

inactive=time

非活动时长

5、fastcgi\_cache zone | off;

调用指定的缓存空间来缓存数据

可用位置:http, server, location

6、fastcgi\_cache\_key string;

定义用作缓存项的key的字符串

示例:fastcgi\_cache\_key $request\_rui;

7、fastcgi\_cache\_methods GET | HEAD | POST ...;

为哪些请求方法使用缓存

8、fastcgi\_cache\_min\_uses number;

缓存空间中的缓存项在inactive定义的非活动时间内至少要被访问到此处所指定的次数方可被认作活动项

9、fastcgi\_keep\_conn on | off;

收到后端服务器响应后,fastcgi服务器是否关闭连接,建议启用长连接

10、fastcgi\_cache\_valid [code ...] time;

不同的响应码各自的缓存时长

示例:

注:也要放在context:http里

http {

fastcgi\_cache\_path /var/cache/nginx/fcgi\_cache levels=1:2:1 keys\_zone=fcgicache:20m inactive=120s;

...

server {

location ~* \.php$ {

...

fastcgi\_cache fcgicache;

fastcgi\_cache\_key $request\_uri;

fastcgi\_cache\_valid 200 302 10m;

fastcgi\_cache\_valid 301 1h;

fastcgi\_cache\_valid any 1m;

...

}

}

实验:实现LNMP,提供多个虚拟主机

http, 提供wordpress

https, 提供pma

拓扑图如下

 title=

为了演示,这里把nginx服务器和php-fpm服务器拆开了,实际工作中一般不用拆开。以下是各服务器的配置:

1MySQL服务器

\#192.168.30.6

yum -y isntall mariadb-server #安装MariaDB数据库

mkdir -pv /data/binlog #创建用于独立存放二进制日志的目录

chown -R mysql.mysql /data/binlog #更改目录权限

vim /etc/my.cnf #修改配置文件,添加以下内容

log\_bin=/data/binlog/mysql-bin

binlog\_format=row

innodb\_file\_per\_table

character\_set\_server=utf8

 title=

systemctl start mariadb #启动数据库

mysql\_secure\_installation #安全初始化,这里为了实验方便就不做了

MariaDB [none]> create database wpdb; #创建wordpress数据库

MariaDB [none]> grant all on wpdb.* to wpuser@'192.168.30.%' identified by 'centos'; #创建wordpress帐号

MariaDB [none]> grant all on *.* to pmauser@'192.168.30.%' identified by 'centos'; #创建pma帐号

MariaDB [none]> flush privileges; #刷新权限

2php-fpm服务器

\# 192.168.30.5

yum -y install php-fpm php-mysql

systemctl start php-fpm

mkdir -pv /data/wind/ #创建主目录

布署phpMyadmin

下载pma:https://www.phpmyadmin.net/downloads/

tar xvf phpMyAdmin-4.0.10.20-all-languages.tar.xz -C /data/wind

cd /data/wind/

mv phpMyAdmin-4.0.10.20-all-languages pma

cd pma

cp config.sample.inc.php config.inc.php

vim config.inc.php

$cfg['blowfish\_secret'] = 'abc1234'; #红色的随机数改一下

$cfg\['Servers'\]\[$i]['host'] = '192.168.30.6'; #MySQL服务器的地址改成192.168.30.6

 title=

yum -y install php-mbstring

布署wordpress

下载地址:

官网:https://cn.wordpress.org/

解压缩WordPress博客程序到/data/wind/wordpress下

tar xvf wordpress-4.9.4-zh\_CN.tar.gz -C /data/wind/

 title=

cd /data/wind/wordpress

cp -a wp-config-sample.php wp-config.php

vim wp-config.php 修改相应选项

 title=

setfacl -R -m u:apache:rwx /data/wind/wordpress #增加acl权限

3nginx服务器

\#192.168.30.3

yum -y install nginx #安装nginx

mkdir -pv /data/wind/

tar xvf wordpress-4.9.4-zh\_CN.tar.gz -C /data/wind/

tar xvf phpMyAdmin-4.0.10.20-all-languages.tar.xz -C /data/wind

cd /data/wind/

mv phpMyAdmin-4.0.10.20-all-languages pma

\# nginx服务器也要解压一份wordpress和pma,因为静态页面无法交给php-fpm服务器去处理,所以本机要放一份,不过可以只留下静态页面。实际工作中nginx服务器和php-fpm服务器不需要拆开,只解压一份即可,这里拆分开仅作为演示用

cd /etc/pki/tls/certs

make wind.crt #为了启用https服务,自签名一个证书wind.crt,顺便也生成了一个私钥wind.key

 title=

openssl rsa -in wind.key -out wind.key #为了方便,去掉私钥的密码,需要输一遍原密码

mv /etc/pki/tls/certs/wind* /etc/nginx/conf.d/ #证书和私钥移到另一个目录

\# nginx可以选择启不启用fastcgi日志,这里不启用

vim /etc/nginx/conf.d/wind.conf #为LNMP单起一个配置文件

server {

listen 80 default\_server; #80端口用于wordpress

server\_name www.wind.com; #指定虚拟主机名

root /data/wind/wordpress; #设置web资源的路径映射

index index.html index.php; #指定主页

location ~* \.php$ { #起一个处理php文件的location

fastcgi\_pass 192.168.30.5:9000; #指定php-fpm服务器

fastcgi\_index index.php;

fastcgi\_param SCRIPT\_FILENAME /data/wind/wordpress$fastcgi\_script\_name;

#上一行中,/data/wind/wordpress换成$document\_root也可以

include fastcgi\_params;

}

location / { #单起一个location,用以处理静态页面

}

}

server {

listen 443 ssl; #443端口用于pma

server\_name www.wind.com;

root /data/wind/pma;

index index.html index.php

ssl\_certificate /etc/nginx/conf.d/wind.crt;

ssl\_certificate\_key /etc/nginx/conf.d/wind.key;

ssl\_session\_cache shared:sslcache:20m;

ssl\_session\_timeout 10m;

location ~* \.php$ {

fastcgi\_pass 192.168.30.5:9000;

fastcgi\_index index.php;

fastcgi\_param SCRIPT\_FILENAME $document\_root$fastcgi\_script\_name;

include fastcgi\_params;

}

location / {

}

}

 title=

\# 由于在/etc/nginx/conf.d/wind.conf中定义了default\_server,因此在/etc/nginx/nginx.conf中要把default\_server去掉

vim /etc/nginx/nginx.conf

server {

listen 80 default\_server; #删掉这行的default\_server字样

listen [::]:80 default\_server; #删掉这行的default\_server字样

 title=

nginx -t #检查nginx配置文件是否有问题

nginx #启动nginx服务

4、客户端

\#192.168.30.2

vim /etc/hosts

192.168.30.3 www.wind.com #添加这一行DNS配置

打开火狐浏览器,输入http://www.wind.com,打开wordpress成功

 title=

输入https://www.wind.com,打开pma成功

 title=

wordpress输入注册信息,安装成功

 title=

pma输入数据库用户名pmauser和密码centos,登录成功

 title=

ngx\_http\_upstream\_module模块

ngx\_http\_upstream\_module模块

用于将多个服务器定义成服务器组,而由proxy\_pass, fastcgi\_pass等指令进行引用

1、upstream name { ... }

定义后端服务器组,会引入一个新的上下文

默认调度算法是wrr

Context: http

upstream httpdsrvs {

server ...

server...

...

}

2、server address [parameters];

在upstream上下文中server成员,以及相关的参数;Context:upstream

address的表示格式:

unix:/PATH/TO/SOME\_SOCK\_FILE

IP[:PORT]

HOSTNAME[:PORT]

parameters:

weight=number 权重,默认为1

max\_conns 连接后端报务器最大并发活动连接数,1.11.5后支持

max\_fails=number 失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用,默认为1

fail\_timeout=time 后端服务器标记为不可用状态的连接超时时长,默认10s

backup 将服务器标记为“备用”,即所有服务器均不可用时才启用

down 标记为“不可用”,配合ip\_hash使用,实现灰度发布

注:最好总结一下lvs和nginx有哪些调度算法

3、ip\_hash 源地址hash调度方法

4、least\_conn 最少连接调度算法,当server拥有不同的权重时其为wlc,当所有后端主机连接数相同时,则使用wrr,适用于长连接

5、hash key [consistent] 基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者组合

作用:将请求分类,同一类请求将发往同一个upstream server,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用

hash $request\_uri consistent;

hash $remote\_addr;

不加consistent:hash(1.html)%2= 0 1 2 --> 结果太少,容易发生哈希环偏斜

加consistent:hash(1.html) %2^32=大哈希环

6、keepalive 连接数N;

为每个worker进程保留的空闲的长连接数量,可节约nginx端口,并减少连接管理的消耗

7、health\_check [parameters];

健康状态检测机制;只能用于location上下文

常用参数:

interval=time检测的频率,默认为5秒

fails=number:判定服务器不可用的失败检测次数;默认为1次

passes=number:判定服务器可用的失败检测次数;默认为1次

uri=uri:做健康状态检测测试的目标uri;默认为/

match=NAME:健康状态检测的结果评估调用此处指定的match配置块

注意:仅对nginx plus有效(付费)

8、match name { ... }

对backend server做健康状态检测时,定义其结果判断机制;只能用于http上下文

常用的参数:

status code[ code ...]: 期望的响应状态码

header HEADER[operator value]:期望存在响应首部,也可对期望的响应首部的值基于比较操作符和值进行比较

body:期望响应报文的主体部分应该有的内容

注意:仅对nginx plus有效

ngx\_stream\_core\_module模块

nginx的其它的二次发行版:

Tengine:由淘宝网发起的Web服务器项目。它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能和特性。Tengine的性能和稳定性已经在大型的网站如淘宝网,天猫商城等得到了很好的检验。它的最终目标是打造一个高效、稳定、安全、易用的Web平台。从2011年12月开始,Tengine成为一个开源项目,官网 http://tengine.taobao.org/

OpenResty:基于 Nginx 与 Lua 语言的高性能 Web 平台

ngx\_stream\_core\_module模块

模拟反代基于tcp或udp的服务连接,即工作于传输层的反代或调度器

1、stream { ... }

定义stream相关的服务;Context:main

stream {

upstream mysqlsrvs {

server 192.168.22.2:3306;

server 192.168.22.3:3306;

least\_conn;

}

server {

listen [10.1.0.6:]3306;

proxy\_pass mysqlsrvs;

}

}

例如可以实现对后端多个MySQL数据库的调度

2、listen格式

listen address:port [ssl] [udp] [proxy\_protocol] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so\_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

ngx\_stream\_proxy\_module模块

ngx\_stream\_proxy\_module模块

可实现代理基于TCP,UDP (1.9.13), UNIX-domain sockets的数据流

1 proxy\_pass address;

指定后端服务器地址

2 proxy\_timeout timeout;

无数据传输时,保持连接状态的超时时长

默认为10m

3 proxy\_connect\_timeout time;

设置nginx与被代理的服务器尝试建立连接的超时时长

默认为60s

示例

stream {

upstream mysqlsrvs {

server 192.168.0.10:3306;

server 192.168.0.11:3306;

hash $remote\_addr consistent;

}

server {

listen [172.16.100.100:]3306;

proxy\_pass mysqlsrvs;

proxy\_timeout 60s;

proxy\_connect\_timeout 10s;

}

}

练习

•nginx--> AMPs(wordpress)

•nginx--> FPMs(wordpress)

•自定义错误404和5xx错误页,文本静态内容传输压缩

•实现动静分离:动态资源存储一组服务器、图片资源存在一组服务器、静态的文本类资源存储在一组服务器

nginx-->images servers ( imgs.wind.com)

location ~* \.(jpg|png|gif|jpeg)$ {

...

}

nginx-->dynamic content servers (shop.wind.com)

location ~* \.php$ {

...

}

标签: none

相关文章推荐

添加新评论,含*的栏目为必填