Nginx(发音同 engine x)是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页伺服器中表现较好。
一、安装nginx
1. 添加nginx用户
1
2
|
[root@web ~]
# groupadd -r nginx
[root@web ~]
# useradd -r -M -s /sbin/nologin -g nginx nginx
|
2. 安装nginx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
[root@web ~]
# tar xf nginx-1.4.6.tar.gz
[root@web ~]
# cd nginx-1.4.6
[root@web nginx-1.4.6]
# ./configure --prefix=/usr/local/ \
--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 \
--pid-path=
/var/run/nginx/nginx
.pid \
--lock-path=
/var/lock/nginx
.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_gzip_static_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/fcgi/
\
--with-pcre=
/root/pcre-8
.32
[root@web nginx-1.4.6]
# make && make install
|
3. 为nginx添加启动脚本
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
|
#!/bin/sh
#
# 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
|
4. 简单配置和启动
1
2
3
4
5
6
7
8
|
[root@web ~]
# vim /etc/nginx/nginx.conf
user nginx;
pid
/var/run/nginx
.pid;
[root@web ~]
# service nginx restart
nginx: the configuration
file
/etc/nginx/nginx
.conf syntax is ok
nginx: configuration
file
/etc/nginx/nginx
.conf
test
is successful
Stopping nginx: [ OK ]
Starting nginx: [ OK ]
|
二. 配置nginx
1) location
语法规则: location [=|~|~*|^~] /uri/ { … }
= | 表示精确匹配,不会去匹配子目录下的文件 |
~ | 表示区分大小写的正则匹配 |
~* | 表示不区分大小写的正则匹配 |
^~ | 表示不做正则表达式匹配 |
/ | 表示通用匹配,任何请求都会匹配到 |
2) root
语法规则:root PATH (可以用在http、server、location中)
root用来指定网站的根目录
3)alias
语法规则:alias file-path|directory-path
alias的普通用法:
location /alias/test.html {
alias /web/alias/test.html;
}
使用正则表达式的alias:
location ~ ^/test/(.*)$ {
alias /var/nginx/test/$1;
}
如果root在/var/www/html下,而访问http://domain/alias/test.html这个目录时,就会访问web下alias/test.html
root和alias的区别:
root指定的目录就是location后面的“/”,而alias指定的目录需要包括location后面的路径,如上面的例子。
4) index
语法规则:index index.html index.htm; #指定主页文件
autoindex on; #索引功能打开,当没有找到定义的主页文件时,就会把网站跟目录下的文件都列出来
5) 基于主机的访问控制
allow [ address | CIDR | all ]
deny [ address | CIDR | all ]
例子:
location / {
root /var/www/html;
index index.html index.htm;
allow 192.168.2.0/24;
deny all;
}
6) 定义虚拟主机
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
server {
listen 80 default;
server_name _;
location / {
root
/var/nginx/test
;
index index.html;
}
}
server {
listen 80;
server_name www.aa.com;
location / {
root
/var/www/html
;
index index.html index.htm;
}
}
#定义了2个虚拟主机,上面一个是默认虚拟主机
|
7) 基于用户认证的nginx监控
1
2
3
4
5
6
7
8
9
|
[root@web ~]
# htpasswd -m -c /etc/nginx/.htpasswd maria
[root@web ~]
# vim /etc/nginx/nginx.conf
location
/nginx_status
{
stub_status on;
#打开监控功能
access_log off;
#关闭日志
auth_basic
"who are you?"
;
#认证时的提示信息
auth_basic_user_file
/etc/nginx/
.htpasswd;
#认证的文件
}
#在编译时需添加--with-http_stub_status_module这个模块,才可以开启监控
|
8)URL重写
语法规则: rewrite regex replacement flag
flag的种类:
last | 把当前的重写指令执行结束,并且重新启动匹配进程,一般都是用last |
break | 中止Rewirte,不在继续匹配 |
redirect | 返回临时重定向的HTTP状态302 |
permanent | 返回永久重定向的HTTP状态301 |
统一资源定位符(URL)和统一资源标识符(URI):
www.aa.com/nginx/a.html,对于这个地址,可以理解为这个地址就是一个URL,/nignx/a.html就是URI。就相当于一个绝对路径,一个相对路径。
例子:
http://www.aa.com/maria.php?id=123 #用户请求的地址
http://www.aa.com/123/maria #重写后的地址
rewrite ^/(maria)\.php\?id=(.*)$ /$2/$1 last; #书写方法,前面匹配的就是URI
9)if语句
语法规则: if (condition) { ... }
应用环境: server, location
congdition:
1、变量名; false values are: empty string ("", or any string starting with "0";)
2、对于变量进行的比较表达式,可使用=或!=进行测试;
3、正则表达式的模式匹配:
~ 区分大小的模式匹配
~* 不区分字母大小写的模式匹配
!~ 和 !~* 分别对上面的两种测试取反
4、测试文件是否存在-f或!-f
5、测试目录是否存在-d或!-d
6、测试目录、文件或链接文件的存在性-e或!-e
7、检查一个文件的执行权限-x或!-x
简单应用:
1
2
3
4
5
6
7
8
9
|
#实现域名跳转
server
{
listen 80;
server_name jump.aa.com;
index index.html index.php;
root
/var/www/html
;
rewrite ^/ http:
//www
.aa.com/;
}
|
1
2
3
4
5
6
7
8
|
#简单的防盗链配置:
location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers none blocked www.aa.com;
if
($invalid_referer) {
rewrite ^/ http:
//www
.aa.com
/403
.html;
# return 404
}
}
|
10) 日志管理
语法规则: log_format name format
Ⅰ、设定错误日志格式及级别:
1
2
3
4
5
6
7
|
http {
log_format my_log_fm
'$http_x_forwarded_for - $remote_user [$time_local]'
'"$request" $status $body_bytes_sent'
'"$http_referer" "$http_user_agent"'
;
access_log
/var/log/nginx/access
.log my_log_fm;
error_log
/var/log/nginx/error
.log warn;
}
|
$http_x_forwarded_for
和$remote_user用于记录客户端网关的IP地址和用户
$time_local用于记录访问时间和时区
$request用于记录请求的URL和http协议
$status用于记录请求的状态,例如请求成功时状态码为200
$body_bytes_sent用于记录发送给客户端文件主体的内容大小
$http_referer用户记录请求是从哪个页面连接访问过来的
$http_user_agent用户记录客户端浏览器的相关信息
Ⅱ、记录类似apache格式的日志:
1
2
3
4
|
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
/var/log/nginx/access
.log main;
|
Ⅲ、启用日志缓存:
open_log_file_cache max=100 inactive=30s min_uses=2 valid=1m;
max | 最多在缓存中最大文件描述符的数量 |
inactive | 在固定时间内没有被访问过的文件描述符,就从缓存中移除 |
min_uses | 在inactive的时间内,被访问的最少次数,满足这个次数才放到缓存中 |
vaild | 检查缓存中的日志在磁盘上是否还存在,m表示分钟 |
off | 关闭日志缓存功能 |
Ⅳ、日志切割
nginx的日志文件没有rotate功能。如果你不处理,日志文件将变得越来越大,可以用脚本+crontab来进行日志切割。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[root@web ~]
# vim log_switch.sh
#!/bin/bash
#
logs_path=
"/var/log/nginx/"
#当前日志的存放目录
mkdir
-p ${logs_path}$(
date
-d
"yesterday"
+
"%Y"
)/$(
date
-d
"yesterday"
+
"%m"
)
#在上面的目录下,给日志创建以时间命名的目录
mv
${logs_path}aa.access.log ${logs_path}$(
date
-d
"yesterday"
+
"%Y"
)/$(
date
-d
"yesterday"
+
"%m"
)/$(
date
-d"yest
erday
" +"
%Y%m%d").log
#移动日志到日期命名的目录中
service nginx reload
[root@web ~]
# crontab -e
00 00 * * *
/root/log_switch
.sh
|
11. 设定限速
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#为某个特定路径限速
server {
server_name www.aa.com;
location
/downloads/
{
limit_rate 256k;
limit_rate_after 20m;
root
/var/www/html
;
}
..
}
#限制搜索引擎的速度
if
($http_user_agent ~ Google|Yahoo|MSN|baidu) {
limit_rate 128k;
}
|
limit_rate_after
20m表示下载的前20M不做限速
limit_rate限制速度为256K/s
12. 为反向代理启用缓存功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
http {
proxy_cache_path
/data/nginx/cache
levels=1:2 keys_zone=STATIC:10m
inactive=24h max_size=1g;
server {
location / {
proxy_pass http:
//192
.168.2.87;
proxy_set_header Real-ip $remote_addr;
proxy_cache STATIC;
proxy_cache_valid 200 1d;
#对响应码为200的文件,指定缓存失效的检查时间
client_max_body_size 50m;
client_body_buffer_size 256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 256k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
}
}
}
|
levels 指定该缓存空间有两层hash目录,第一层目录为1个字母,第二层为2个字母
keys_zone=STATIC:1m 参数用来为这个缓存区起名(proxy_cache 指令需要用到其后对应缓存区名称),:1m 指内存缓存空间大小为1MB
inactive=24h指如果缓存数据在24小时(天:d、秒:s、分:m)内没有被访问,将自动被删除
max_size=1g 指硬盘缓存大小为1g
13. 负载均衡功能
1
2
3
4
5
|
upstream backend {
server www.aa.com weight=5 down [backup];
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:
/tmp/backend3
;
}
|
weight 设定权重,默认为1
max_fails 在fail_timeout指令设定的时间内发往此server的不成功的请求次数,达到此数目后,此服务器将变为不可操作状态;默认值为1;设定为0值则禁用此功能;
fail_timeout 默认为10秒;
down 列表中有这个服务器,但是不启用它
backup 当其他负载均衡的服务器都挂了,才会启用backup
本文出自 “My favorite technology” 博客,请务必保留此出处http://svenman.blog.51cto.com/6867097/1377724