|
Nginx介绍
Nginx("engine x")是一个高性能的http和反向代理服务,也是一个IMAP/POP3/SMTP代理服务器。由lgorsysoev为俄罗斯访问量第二的Rambler.ru站点开发。Nginx因为它的稳定性,丰富的功能及低内存消耗等特性而闻名,目前国内各大门户网站已经部署了Nginx,如新浪网易,腾讯等。
一、Nginx特性:
(1)模块化设计,较好的扩展性
(2)高可靠性
master主控进程-->worker子进程,缓存加载
(3)低内存消耗
(4)支持热部署:
不停机而更新配置文件、日志文件、升级程序
(5)支持事件驱动、AIO(异步IO)、mmap(内存映射)
二、基本功能:
(1)静态资源的web服务器,能缓存打开的文件描述符
(2)能做http、smtp、pop3协议的反向代理服务器
反向代理服务器:客户端请求发到反向代理服务器,数据再封装后再发给服务器,反向代理可经过多个,服务器回应的数据再通过代理服务器封装后发给客户端
(3)缓存、负载均衡
负载均衡:客户端请求到代理服务器,再由代理服务器分发到不同的服务器
(4)支持FastCGI(fpm,lnmp),uwsgi(python)等
(5)模块化(非DSO机制)、过滤器zip、SSI及图像的大小调整
(6)支持SSL
三、扩展功能:
基于名称和IP的虚拟主机
支持keepalive
支持平滑升级
定制访问日志、支持使用日志缓冲区提供日志存储性能
支持url rewrite
支持路径别名
支持基于IP及用户的访问控制
支持速率限制,支持并发数限制
四、Nginx的基本架构
一个master进程,生成一个或多个worker进程
事件驱动:epoll(边缘触发,linux)、kqueue(BSD),/dev/poll(WINDOWS)
复用器:select
支持sendfile,sendfile64
支持AIO
支持mmap
nginx的工作模式:非阻塞、事件驱动、由一进程生成多个worker线程,每个worker响应多个请求
五、模块类型:
standard HTTP modules 标准HTTP模块
optional HTTP modules 可选模块
mail modules 邮件模块
3rd party modules 第三方模块
六、配置文件
main配置段://核心模块
event:event模型工作特性
http:http协议相关配置
配置指令以分号结尾,语法格式
directive value1 ...
支持使用变量
内置变量
模块提供内建变量
自定义变量
set var_name value
七、基本配置的类别
1、用于调试、定位问题
2、正常运行配置
3、优化性能配置
4、事件相关配置
详解Nginx的配置
(1)正常运行的必备配置:
1
2
3
4
5
6
7
8
| 1、user USERNAME [GROUPNAME];
指定运行worker进程的用户和组;
user nginx nginx;
2、pid /path/to/pid_file;
指定nginx守护进程的pid文件;
pid /var/run/nginx/nginx.pid;
3、worker_rlimit_nofile #;
指定所有worker进程所能够打开的最大文件数;
|
(2)性能优化相关的配置:
1
2
3
4
5
6
7
8
9
10
| 1、worker_processes #; 进程数
worker进程的个数;通常应该略少于CPU物理核心数;
2、worker_cpu_affinity cpumask ...; 绑定CPU
把工作进程绑定到CPU的设置
3、timer_resolution interval; 计时器解析度
计时器解析度;降低此值,可减少gettimeofday()系统调用的次数;
4、worker_priority number; 进程nice值
指明worker进程的nice值;
-20, 19
100, 139
|
(3)事件相关的配置:
1
2
3
4
5
6
7
8
9
| 1、accept_mutex off|on;
负载均衡锁打开时能让多个worker轮流地响应请求
2、lock_file file;
accept_mutex用到的锁文件路径;
3、use [epoll|rtsig|select|poll];
指明使用的事件模型;建议让Nginx自行选择;
4、worker_connections #;
单个worker处理最大连接数,整个最大连接数是与wroker进程数相乘
worker_connections * work_processes
|
(4)用户于调试、定位问题:
1
2
3
4
5
6
7
| 1、daemon {on|off};
是否以守护进程方式运行nginx;调试时应该设置为Off;
2、master_process {on|off};
是否以master/worker模型来运行nginx; 调试时可以设置为off;
3、error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
error_log 位置 级别;
若要使用debug级别,需要在编译nginx时使用了--with-debug选项;
|
总结:常需要进行调整的参数
worker_processes, 略少于CPU数
worker_connections, 51200
worker_cpu_affinity, 绑定CPU cpumask
worker_priority -10
新改动配置生效的方式:
#nginx -s reload
八、Nginx作为web服务器时使用的配置:
http {}:由ngx_http_core_module模块所引入;
(1)配置框架:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| http {
upstream {
...
}
server {
location URL {
root "/path/to/somedir";
...
} # 类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系;
location URL {
if ... {
...
}
}
} # 每个server类似于httpd中的一个<VirtualHost>;
server {
...
}
}
注意:与http相关的指令仅能够放置于http、server、location、upstream、if上下文,但有些指令仅应用于这5种上下文中的某些种;
|
(2)配置指令:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
| 1、server {}
定义一个虚拟主机;
server {
listen 8080;
server_name www.magedu.com;
root "/vhosts/web1";
}
2、listen
指定监听的地址和端口;
listen address[:port];
listen port;
3、server_name NAME [...];
后可跟多个主机;名称还可以使用正则表达式(~)或通配符;
(1) 先做精确匹配检查;
(2) 左侧通配符匹配检查:*.magedu.com
(3) 右侧通配符匹配检查:如mail.*
(4) 正则表达式匹配检查:如 ~^.*\.magedu\.com$
(5) default_server;
server {
server_name www.magedu.com;
}
server {
server_name *.magedu.com;
}
server {
server_name mail.*
}
4、root path;
设置资源路径映射;用于指明请求的URL所对应的资源所在的文件系统上的起始路径;
5、location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
根据请求URI配置location,可做访问控制,支持正则表达式和通配符
=:精确匹配检查;
~: 正则表达式模式匹配检查,区分字符大小写;
~*: 正则表达式模块匹配检查,不区分字符大小写;
^~:URI的前半部分匹配,不支持正则表达式;
匹配的优先级:精确匹配(=)、^~、~、~*、不带任何符号的location;
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
“/” 匹配A
“/index.html” 匹配B
“/documents/document.html” 匹配C
“/images/1.gif” 匹配D
“/documents/1.jpg” 匹配E
6、alias path;
用于location配置段,定义路径别名
location /images/ {
root "/vhosts/web1";
}
http://www.magedu.com/images/a.jpg <-- /vhosts/web1/images/a.jpg
location /images/ {
alias "/www/pictures";
}
http://www.magedu.com/images/a.jpg <-- /www/picuter/a.jpg
注意:root表示指明路径为对应的location "/" URL; alias表示路径映射,即location指令后定义的URL是相对于alias所指明的路径而言;
7、index file;
默认主页面;
index index.php index.html;
8、error_page code ... [=[response]] uri;
根据http响应状态码来指明特用的错误页面;
#vim /vhosts/web1/404_customed.html
#vim /etc/nginx/nginx.conf
location / {
error_page 404 /404_customed.html;
}
[=[response]]:以指定的响应码进行响应,而不是默认的原来的响应;默认表示以新资源的响应码为其响应码;
9、基于IP的访问控制
allow IP/Network;
deny IP/Network;
#vim /etc/nginx/nginx.conf
location / {
deny 172.16.100.6;
}
#/usr/local/nginx/sbin/nginx -t //测试语法
#/usr/local/nginx/sbin/nginx -s reload
10、基于用户的访问控制
basic, digest;
auth_basic "";
auth_basic_user_file "/PATH/TO/PASSWORD_FILE"
账号密码文件建议使用htpasswd来创建;
#vim /etc/nginx/nginx.conf
location / {
auth_basic "only for VIP";
auth_basic_user_file /etc/nginx/users/.htpasswd;
}
#mkdir -p /etc/nginx/users
#cd /etc/nginx/users
#htpasswd -c -m /etc/nginx/users/.htpasswd tom
添加密码
#/usr/local/nginx/sbin/nginx -t //测试语法
#/usr/local/nginx/sbin/nginx -s reload
11、https服务
生成私钥,生成证书签署请求,并获得证书;
CA服务端:
#cd /etc/pki/CA
#(umask 077;openssl genrsa -out private/cakey.pem 2048)
#openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 30000
CN,HA,ZZ,magedu,ops,ca.magedu.com,caadmin@admin.com
#touch servial index.txt
#echo 01 > servial
CA客户端
#cd /etc/nginx
#mkdir ssl
#cd ssl
#(umask 077;openssl genrsa -out nginx.key 1024)
#openssl req -new -key nginx.key -out nginx.csr
CN,HA,ZZ,magedu,ops,www.magedu.com,web@admin.com
CA服务端
#openssl ca -in nginx.csr -out nginx.crt -days 3650
CA客户端:
#vim /etc/nginx/nginx.conf
server {
listen 443 ssl;
server_name www.magedu.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 /vhosts/web1;
index index.html index.htm;
}
}
#/usr/local/nginx/sbin/nginx -t //测试语法
#/usr/local/nginx/sbin/nginx -s reload
12、stub_status {on|off};
仅能用于location上下文;
location /status {
stub_status on;
allow 172.16.0.0/16;
deny all;
}
结果示例:
Active connections: 6 # 当前所有处于打开状态的连接数;
server accepts handled requests
241 241 431
(1) 已经接受过的连接数
(2) 已经处理过的连接数
(3) 已经处理过的请求数;在“保持连接”模式下,请求数量可能会多于连接数量;
Reading: 0 Writing: 1 Waiting: 5
Reading:正处于接收请求状态的连接数;
Writing: 请求已经接收完成,正处于处理请求或发送响应的过程中的连接数;
Waiting:保持连接模式,且处于活动状态的连接数;
13、rewrite regex replacement flag;
例如:
...
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;
....
http://www.magedu.com/images/a/b/c/1.jpg --> http://www.magedu.com/imgs/a/b/c/1.jpg
flag:
last:一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理;而是由User Agent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break:一旦此rewrite规则重写完成后,由User Agent对新的URL重新发起请求,且不再会被当前locatrion内的任何rewrite规则所检查;
redirect:以302响应码(临时重定向)返回新的URL;
permanent:以301响应码(永久重定向)返回新的URL;
14、if
语法:if (condition) {...}
应用环境:server, location
condition:
(1) 变量名;
变量值为空串,或者以“0”开始,则为false;其它的均为true;
(2) 以变量为操作数构成的比较表达式
可使用=, !=类似的比较操作符进行测试;
(3) 正则表达式的模式匹配操作
~: 区分大小写的模式匹配检查
~*: 不区分大小写的模式匹配检查
!~和!~*:对上面两种测试取反
(4) 测试路径为文件可能性:-f, !-f
(5) 测试指定路径为目录的可能性:-d, !-d
(6) 测试文件的存在性:-e, !-e
(7) 检查文件是否有执行权限:-x, !-x
例如:
if ($http_user_agent ~* MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
http_user_agent 客户端浏览器
MSIE 微软浏览器
15、防盗链
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referer none blocked www.magedu.com;
if ($invalid_referer) {
rewrite ^/ http://www.magedu.com/403.html;
}
}
valid_referer none blocked 定义合法引用
16、定制访问日志格式
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各模块内建变量;
|
九、安装方法:
源码:编译安装
程序包:rpm
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
| 1、安装gcc开发环境
#yum -y instal "Development tools" "Server Platform Development"
2、安装 pcre-devel openssl-devel
#yum -y install pcre-devel openssl-devel
#设置用户
#groupadd -r nginx
#useradd -r -g nginx nginx
4)下载nginx-1.4.7稳定版
# wget http://nginx.org/download/nginx-1.4.7.tar.gz
编译安装
# tar xf nginx-1.4.7.tar.gz
# cd nginx-1.4.7
# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_module --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fastcgi --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi
# make && make install
# mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi,uwsgi}
5)检测配置文件语法
# /usr/sbin/nginx -t
6) 提供启动脚本
# vim /etc/rc.d/init.d/nginx
内容如下
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
7)添加到系统服务并开机启动
# chkconfig --add nginx
# chkconfig nginx on
# chkconfig --list nigx
8) 设置nginx配置文件的语法高亮
# mkdir ./vim/syntax -pv
# cd .vim/syntax
# wget http://www.vim.org/scripts/download_script.php?src_id=19394
# cd .vim
# vim filetype.vim 内容如下
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* if &ft == '' | setfiletype nginx | endif
9)启动服务
# service nginx start
# pa aux | grep nginx
至此,编译及后续工作完成
|
|
|
|