nginx:
nginx是俄罗斯软件工程师Igor Sysoev开发的免费开源web服务器软件,nginx采用了模块化、事件驱动、异步、单线程及非阻塞的架构,并大量采用了多路复用及事件通知机制来实现高并发和高性能,解决C10K的问题,主要功能就是提供http和反向代理服务,以及邮件服务及反向代理等,并且具有多种web服务器功能特性:负载均衡,缓存,访问控制,带宽控制,以及高效整合各种应用的能力。
在nginx中,连接请求由为数不多的几个仅包含一个线程的进程worker以高效的回环(run-loop)机制进行处理,而每个worker可以并行处理数千个的并发连接及请求。
nginx特性:
1、 模块化设计,较好的扩展性;
2、 高可靠性:由一个master主进程和多个worker子进程
3、 支持热部署:平滑升级版本
不停机更新配置文件、更换日志文件、更新服务器程序版本
4、 低内存消耗
10000个keep-alive连接模式下的非活动连接仅消耗2.5M内存
nginx的基本功能:
静态资源的web服务器;
http协议的反向代理服务器
pop3/imap4协议反向代理服务器
FastCGI,uWSGI等协议;
模块化(非DSO),不支持动态装卸载
一、nginx的配置详解(用淘宝研发的tengine作为例子):
1
2
3
4
5
6
7
8
9
10
11
12
13
user nginx nginx; //指定用于运行worker进程的用户和组
worker_processes 4; //指定nginx运行的子进程数,通过时CPU核心数-1
error_log logs/error.log info; //全局错误日志,类型为info
pid logs/nginx.pid; //nginx运行时的PID
worker_rlimit_nofile_number 2048; //当个worker进程所能打开的最大连接数
worker_rlimit_sigpending 100; //指定每个用户能够发往worker进程的信号的数量
worker_cpu_affinity cpumask ...; 和cpu做绑定,主要作用是均衡的使用cpu
4颗cpu的话:
worker_cpu_affinity 0001 0010 0100 1000;
worker_priority nice : 调整work子进程的nice值
设定工作模式及连接数:
1
2
3
4
5
6
7
8
events {
worker_connections 1024; //单个worker能响应的最大并发连接数
use [epoll|rgsig|select|poll]; //定义使用的事件模型;建议让Nginx自动选择
accept_mutex [on|off];
//内部调用用户请求至各worker时用的负载均衡锁;打开时表示能让多个worker轮流地、序列化地与响应新请求;
lock_file /path/to/lock_file; //锁文件,
accept_mutex_delay #ms; //内部调用用户请求至各worker时的延迟时间
}
设定http服务:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
http {
include mime.types; //设定mime类型,类型由mime.type文件定义
default_type application/octet-stream;
#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; //访问日志的存放路径
sendfile on; //sendfile函数,对于普通应用,必须设为on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
tcp_nopush on; // 是否启用TCP_NOPUSH(FREEBSE)或TCP_CORK(Linux)选项;仅在sendfile为on时有用;
keepalive_timeout 65; // 设定keepalive连接的超时时长;0表示禁止长连接;默认为75s;
tcp_nodelay on|off; // 对keepalive模式下的连接是否使用TCP_NODELAY选项;
gzip on; // 是否启用gzip压缩报文的body
keepalive_requests number; //在keepalived连接上所允许请求的最大资源数量;默认为100;
keepalive_disable none | browser ...; //指明禁止为何种浏览器使用keepalive功能;
send_timeout 60; //向客户端发送响应报文的超时时长,默认为60s
client_body_buffer_size 512k; //接收客户请求报文body的缓冲区大小;默认为16k;超出此指定大小时,其将被移存于磁盘上
client_body_temp_path path [level1 [level2 [level3]]]; //设定用于存储客户端请求报文的body的临时存储路径及子目录结构和数量;
client_header_buffer_size 1k; //设置客户请求报文首部的缓冲区大小
large_client_header_buffers 4 4k; //设置请求报文大首部的缓冲区大小
aio on|off; //是否打开异步传输的功能,默认是关闭的
directio size|off; //设置直接IO的大小及是否关闭
open_file_cache max=65535 inactive=20s; //是否开启文件描述符缓存
open_file_cache_errors on | off //是否缓存找不到其路径的文件,或没有权限没有权限访问的文件相关信息
open_file_cache_valid 30s; //每隔多久检查一次缓存中缓存项的有效性;默认为60s;
open_file_cache_min_uses number 1 //缓存项在非活动期限内最少应该被访问的次数,指定被访问次数的多少才算是最少访问
server服务:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
server {
listen 80; //监听的端口
server_name localhost; //虚拟主机名称
access_log logs/host.access.log main; //访问本虚拟机服务的日志
location /admin/ { //匹配客户端请求的URL
root html; //指定Document的路径,在安装目录的html目录下
index index.html index.htm; //默认主页
}
=: URI的精确匹配; location = /admin/
~: 做正则表达式匹配,区分字符大小写;
~*:做正则表达式匹配,不区分字符大小写;
^~:对URI的左半部分匹配,不区分字符大小写;
匹配优先级:精确匹配= > ^~ > ~或~* > 不带符号的URI;
location /images/ {
alias /data/imgs/; //定义location匹配的别名
}
error_page 404 /404.html; //错误页面
error_page 500 502 503 504 /50x.html; //服务器端错误页面
location = /50x.html {
root html;
}
location /download/ {
imit_except GET {
allow 172.16.0.0/16; //只有172.18.0.0的主机能用其他方法,其他主机只能get
deny all;
}
}
location /download/ {
limit rate 20480; //限制客户端每秒钟所能够传输的字节数,默认为0表示无限制
}
二、nginx的模块详解:
1、ngx_http_access_module (实现访问控制)
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
2、ngx_http_auth_basic_module (实现basic认证)
1
2
3
4
5
6
7
2.1 auth_basic string | off 使用http basic认证协议对用户进行认证;
2.2 auth_basic_user_file file; 实现用户认证的账号文件
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.ngxhtpasswd;
}
3、ngx_http_log_module (现实日志功能的模块)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
3.1 log_format name string ...; 定义日志格式及其名称
log_format compression '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
3.2 access_log path [format [buffer=size [flush=time]]];
path: 日志存放路径
format: 日志格式 默认为combined格式
buffer: 日志缓存大小
flush: 刷写时间间隔
3.3 open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]
open_log_file_cache off 关闭日志缓存功能
max: 最大缓存的条目
inactive:缓存的活动时间
min_user: 在缓存时间内的最小使用次数
valid: 检查缓存里文件描述符的有效性
4、ngx_http_stub_status_module (实现显示nginx的状态)
1
2
3
4
5
6
7
8
9
10
location /status {
stub_status;
}
Active connections:当前活动的客户端连接数;
accepts:已经接受的客户端连接总数;
handled:已经处理过后客户端连接总数;
requests:客户端的总的请求数;
Readking:正在读取的客户端请求报文首部的连接数;
Writing:正向其发送响应报文的连接数;
Waiting:等待客户端发出请求的空闲连接数;
5、ngx_http_referer_module (基于请求报文中的Referer首部的值做访问控制)
1
2
3
4
5
6
7
8
9
10
11
12
valid_referers none | blocked | server_names | string ...; 定义合法的请求
none:请求报文不存在referer首部;
blocked:请求报文中存在referer首部,但其没有有效值,或其值非以http://或https://开头
server_names:其值为一个主机名;
arbitrary string:直接字符串,可以使用*通配符;
regular expression:以~起始的正则表达式;
内置变量:$invalid_referer(所有不能符合valid_referer指定定义的引用请求均为不合法引用)
valid_referers none blocked server_names *.,magedu.com magedu.* www.magedu.com/galleries/ ~\.magedu\.;
if ($invalid_referer) {
return 403;
}
6、ngx_http_ssl_module (实现http的加密)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ssl on|off 是否启用SSL
ssl_certificate file; 证书文件路径;
ssl_certificate_key file; 证书对应的私钥文件;
ssl_ciphers ciphers; 指明由nginx使用的加密算法,可以是OpenSSL库中所支持各加密套件;
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
//指明支持的ssl协议版本,默认为后三个;
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
//指明ssl会话缓存机制;
off: 不使用session会话
none: 温和禁止
builtin:使用OpenSSL内置的ssl会话缓存,对机制为各worker私有;
shared:在各worker之间使用一个共享的缓存;
name 缓存空间的名称
size:缓存空间的大小,字节为单位,每1MB内存空间可缓存4000个会话
ssl_session_timeout time;
//ssl会话超时时长;即ssl session cache中的缓存有效时长;默认5分钟
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {
listen 443;
server_name localhost;
ssl on;
ssl_certificate /usr/local/nginx/conf/ssl/nginx.pem;
ssl_certificate_key /usr/local/nginx/conf/ssl/nginx.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
7、ngx_http_rewrite_module (将请求的url基于正则表达式进行重写)
1
2
3
4
5
6
7
8
rewrite regex replacement [flag];
regex:正则表达式,用于匹配用户请求的url;
replacement:重写为的结果;
[flag]:
last:重写完成之后停止对当前uri的进一步处理,改为对其他location的url的新一轮处理;
break:重写完成之后停止对当前uri的处理,转向其后面的其它配置;
redirect:重写完成之后会返回客户端一个临时的重定向,由客户端对新的url重新发起请求(302);
permanent:重写完成之后会返回客户端一个永久的重定向,由客户端对新的url重新发起请求(301);
示例:所有请求http服务下admin的目录的都重定向到https。
1
2
3
location /admin/ {
rewrite /admin/.* redirect ;
}
8、ngx_http_gzip_module (实现对响应报文的压缩,节省资源和带宽)
1
2
3
4
5
6
7
gzip on | off; 启用或禁用gzip压缩响应报文;
gzip_comp_level level; 压缩比,1-9,默认为1;
gzip_disable regex ...; regex是为用于匹配客户端响应器类型的正则表达式;表示对何种浏览器禁止使用压缩功能;
gzip_min_length length; 触发压缩功能的响应报文的最小长度;
gzip_http_version 1.0 | 1.1; 设定启用压缩功能时,协议的最小版本;
gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...; 定义对客户端请求的具有何种请求属性的资源启用压缩功能;如expired则表示对由于使用了expire首部而无法缓存的对象启用压缩功能;
gzip_types mime-type ...; 指明仅对哪些类型的资源执行压缩操作;即压缩过滤器;默认为txt/html
示例:
1
2
3
4
5
6
gzip on;
gzip_http_version 1.0;
gzip_comp_level 6;
gzip_disable msie6;
gzip_min_length 2;
gzip_types text/plain text/css text/xml application/x-javascript application/xml application/json application/java-script;
9、ngx_http_fastcgi_module (实现fastcgi协议)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fastcgi_pass address; fastcgi监听的地址
fastcgi_index name; 定义fastcgi应用的默认主页
fastcgi_param parameter value [if_not_empty] 设定传递给后端fastcgi server参数及其值
fastcgi_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size]; 定义缓存:缓存空间等; 只能用于的上下文 :http
path: 文件系统路径,用于存储缓存的文件数据
levels=#[:#[:#]] 缓存目录层级定义
keys_zone=name:size 内存中用于缓存K/V映射关系的空间名称及大小
name: cache的标识符;
size: 元数据cache大小;
inactive=time: 缓存的非活动的时间
max_size: 缓存空间上限;
fastcgi_cache zone | off; 调用定义过的缓存;
fastcgi_cache_key string; 定义要使用的缓存键
fastcgi_cache_methods GET | HEAD | POST ...; 为请求方法对应的请求进行缓存,默认为GET和HEAD;
fastcgi_cache_min_uses number; 在指定时间内缓存项的最少使用次数
fastcgi_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_503 | http_403 | http_404 | off ...; 是否可使用过期的缓存项响应用户请求;
fastcgi_cache_valid [code ...] time; 对不同响应码的响应设定其可缓存时长;
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
fastcgi_cache_path /var/cache/nginx levels=2:1 keys_zone=fscache:10m inactive=30 max_size=1G; //注意,这个不是定义在server中,而是定义在http中
location ~ \.php$ {
root html;
fastcgi_pass 172.18.250.77:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
include fastcgi_params;
fastcgi_cache fscache;
fastcgi_cache_key $request_uri;
fastcgi_cache_min_users 1;
fastcgi_cache_valid 200 302 10m;
fastcgi_cacge_valid 403 5m;
}
1
2
3
4
5
6
7
8
9
10
11
]# tree . 查看缓存的分级目录
.
├── 9e
│ └── 3
│ └── f46b8508aa08a6f8670fb088b8a9739e
├── eb
│ └── f
│ └── c86156f7dcfecf44876ca30d1bac7feb
└── f1
└── a
└── e251273eb74a8ee3f661a7af00915af1
10、ngx_http_proxy_module (反向代理模块)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
proxy_pass URL ;请求转向的服务器
1、proxy_pass后面的路径不带URI时,其会将location的uri传递给
location /uri/ {
proxy_pass 访问后端主机时请求的是DocumentRoot目录下的/uri/
}
2、location定义其uri时使用了正则表达模式匹配机制,则proxy_pass后的路径必须不能使用uri;
location ~|~* PATTERN {
proxy_pass http://host;
}
3、 proxy_pass后面路径是一个uri时,会将location的uri替换为proxy_pss后端主机的uri
location /uri/ {
proxy_pass http://host/new_uri/ 相当于/uri/映射为后端主机的/new_uri }
proxy_set_header field value; 设定向后端主机发送的请求报文的首部及其值
proxy_set_header X-Real-IP $remote_addr; 向后端主机传递客户端IP
proxy_cache_path path [levels=levels] keys_zone=name:size inactive=time [max_size=size]; //定义缓存代理 只能应用在http中
proxy_cache zone |off; 调用缓存
proxy_cache_key string; 定义缓存键
prox_cache_valid; 为不同的状态码提供缓存
proxy_cache_use_stale error |timeout |invalid_header |updating 使用过期内容来响应客户端,默认为关闭
proxy_cache_purge sting 清理缓存
proxy_cache_methods 为哪种请求方法缓存,默认为get,head
proxy_connect_timeout 与后端服务器建立连接的超时时长,默认为60s,最长为75s
proxy_read_timeout 等待后端发送响应报文的超时时长,默认为60s,两次之间的时长
proxy_send_timeout 向后端服务器发送请求报文的超时时长,默认为60S
1
2
3
4
5
6
7
8
9
10
11
]# tree . 代理缓存
.
├── 9e
│ └── 3
│ └── f46b8508aa08a6f8670fb088b8a9739e
├── eb
│ └── f
│ └── c86156f7dcfecf44876ca30d1bac7feb
└── f1
└── a
└── e251273eb74a8ee3f661a7af00915af1
11、ngx_http_upstream_module (实现负载均衡)
1
2
3
4
5
6
7
8
9
10
11
12
13
1、 upstream name {...} 定义后端服务器组;引入新的上下文;只能用于http上下文
name:名称,直接字符串
2、 server address [parameters] 定义服务器的地址和相关的参数;
address格式:
IP[:port] //给定IP地址
HOSTNAME[:port] //当后端有多个虚拟主机时,应该使用HOSTNAME
unix:/path/to/some__sock_file
[parameters]:参数
weight=number 服务器权重
max_fails=number 最大失败尝试次数
fail_timeout=time 设置多长时间后服务器不可用
backup 设置为sorry server
down 手动把服务器表示为down,不在处理任何用户请求;
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
upstream webserver {
server 172.18.250.76:80 weight=1;
server 172.18.250.77:80 weight=1;
}
location / {
proxy_pass http://webserver;
}
]# curl 172.18.250.75 //实现了负载均衡
Hello httpd
]# curl 172.18.250.75
Hello nginx
]# curl 172.18.250.75
Hello httpd
]# curl 172.18.250.75
Hello nginx
后端服务器的80端口down会自动把服务器剔除,服务起来也会自动加入继续提供服务。
1
2
3
4
5
]# service httpd stop
]# curl 172.18.250.75
Hello nginx
]# curl 172.18.250.75
Hello nginx
1
2
3
4
5
6
ip_hash: 源地址哈希调度算法;只能用在upstream当中
upstream webserver {
server 172.18.250.76:80 weight=1;
server 172.18.250.77:80 weight=1;
ip_hash;
}
1
2
3
4
5
least_conn; 最少连接调度算法:考虑了后端服务器负载,用在upstream中
upstream webserver {
server 172.18.250.76:80 weight=1;
server 172.18.250.77:80 weight=1;
least_conn;
1
2
keepalive connections;
keepalive 32; 定义和后端主机的保持连接个数,一般和后端服务器数量一样
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
health_check [parameters]: 定义后端主机的健康状态检测机制,只能用于location中
参数:
interval=#:检测的频度,默认为5秒
fails=number: 判定为失败的检测次数,默认为1
passes=number: 判定为成功的检测次数,默认为1
uri=uri : 执行健康状态检测时的请求uri,默认请求主页
match=name: 基于哪个match做检测结果"成功"或者“失败”的判断
port=number: 向服务器的哪个端口发起健康状态检测请求,默认为服务器自己的工作端口
match name {....} 仅能用于http上下文;对后端主机做健康状态检测时,定义其结果判断标准
专用指令
status:期望的响应码
status CODE
status !CODE
status CODE-CODE
header ;基于响应首部进行判断
header HEADER=VALUE
header HEADER!=VALUE
header [!]HEADER
header HEADER ~ VALUE
body: 期望的响应报文的主体部分应有的内容;
body~ "BODY"
body!~ "BODY"
注意:health_check和match name 两个选项都是只有商业版本的nginx才会支持
1
2
3
4
hash key [consistent]; 定义调度方法,可自定义基于何种信息(key)进行绑定,用于upstream
hash $remote_addr 根据客户端IP
hash $request_uri 根据请求的URI
hash $cookie_username 根据客户端的cookie
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com