一、前言
二、Nginx安装
三、Nginx的配置文件详解
四、nginx配置之http段
五、其他模块
六、实验
一、前言
http://www.nginx.cn/doc/ nginx安装等各个操作界面介绍
Nginx主要实现两个功能:Web服务器和反向代理
Nginx的模块类型:
核心模块:core module
标准模块:
Stanard HTTP modules
Optional HTTP modules
Mail modules
第三方模块:
cat /etc/nginx/nginx.conf //查看pid文件,例如pid为4664
pidof nginx //也可查看pid
lsof -i:80 //查看80端口对应的程序
二、Nginx安装
1.编译安装 //参考博客
http://nginx.org/en/docs/configure.html
http://www.nginx.cn/install
yum -y install openssl-devel
yum -y install pcre-devel
yum -y install zlib-devel
//这几个会依赖到,解压源码文件后,记得创建链接文件
[root@web nginx]# useradd -u 108 -r -g 108 nginx
实际用到的参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
.
/configure
\
--prefix=
/usr
\
--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/
\
--http-uwsgi-temp-path=
/var/tmp/nginx/uwsgi
\
--with-pcre
|
=======================
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
--prefix=path 定义一个目录,存放服务器上的文件 ,也就是nginx的安装目录。默认使用
/usr/local/nginx
。
--sbin-path=path 设置nginx的可执行文件的路径,默认为 prefix
/sbin/nginx
.
--conf-path=path 设置在nginx.conf配置文件的路径。nginx允许使用不同的配置文件启动,通过命令行中的-c选项。默认为prefix
/conf/nginx
.conf.
--pid-path=path 设置nginx.pid文件,将存储的主进程的进程号。安装完成后,可以随时改变的文件名 , 在nginx.conf配置文件中使用 PID指令。默认情况下,文件名 为prefix
/logs/nginx
.pid.
--error-log-path=path 设置主错误,警告,和诊断文件的名称。安装完成后,可以随时改变的文件名 ,在nginx.conf配置文件中 使用 的error_log指令。默认情况下,文件名 为prefix
/logs/error
.log.
--http-log-path=path 设置主请求的HTTP服务器的日志文件的名称。安装完成后,可以随时改变的文件名 ,在nginx.conf配置文件中 使用 的access_log指令。默认情况下,文件名 为prefix
/logs/access
.log.
--user=name 设置nginx工作进程的用户。安装完成后,可以随时更改的名称在nginx.conf配置文件中 使用的 user指令。默认的用户名是nobody。
--group=name 设置nginx工作进程的用户组。安装完成后,可以随时更改的名称在nginx.conf配置文件中 使用的 user指令。默认的为非特权用户。
--with-select_module --without-select_module 启用或禁用构建一个模块来允许服务器使用
select
()方法。该模块将自动建立,如果平台不支持的kqueue,epoll,rtsig或
/dev/poll
。
--with-poll_module --without-poll_module 启用或禁用构建一个模块来允许服务器使用poll()方法。该模块将自动建立,如果平台不支持的kqueue,epoll,rtsig或
/dev/poll
。
--without-http_gzip_module — 不编译压缩的HTTP服务器的响应模块。编译并运行此模块需要zlib库。
--without-http_rewrite_module 不编译重写模块。编译并运行此模块需要PCRE库支持。
--without-http_proxy_module — 不编译http_proxy模块。
--with-http_ssl_module — 使用https协议模块。默认情况下,该模块没有被构建。建立并运行此模块的OpenSSL库是必需的。
--with-pcre=path — 设置PCRE库的源码路径。PCRE库的源码(版本4.4 - 8.30)需要从PCRE网站下载并解压。其余的工作是Nginx的./ configure和
make
来完成。正则表达式使用在location指令和 ngx_http_rewrite_module 模块中。
--with-pcre-jit —编译PCRE包含“just-
in
-
time
compilation”(1.1.12中, pcre_jit指令)。
--with-zlib=path —设置的zlib库的源码路径。要下载从 zlib(版本1.1.3 - 1.2.5)的并解压。其余的工作是Nginx的./ configure和
make
完成。ngx_http_gzip_module模块需要使用zlib 。
--with-cc-opt=parameters — 设置额外的参数将被添加到CFLAGS变量。例如,当你在FreeBSD上使用PCRE库时需要使用:--with-cc-opt=
"-I /usr/local/include。.如需要需要增加 select()支持的文件数量:--with-cc-opt="
-D FD_SETSIZE=2048".
--with-ld-opt=parameters —设置附加的参数,将用于在链接期间。例如,当在FreeBSD下使用该系统的PCRE库,应指定:--with-ld-opt=
"-L /usr/local/lib"
.
|
# make && make install
====================================================
nginx -s {start,quit,reopen,reload,stop} //quit立即终止,stop平滑终止
-t 测试语法
2.提供服务启动脚本
[root@web nginx-1.4.2]# vim /etc/init.d/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
|
[root@web ~]# chmod +x /etc/init.d/nginx
用service启动,并打开浏览器访问
三、Nginx的配置文件详解
1.nginx的配置文件的组成部分:
主配置文件:nginx.conf
fastcgi,scgi,uwscgi
配置指令(必须以分号结尾):
directive value[va1,va2,va3,...]
支持使用变量:
内部变量:由模块引入,可直接引用
自定义变量:set var_name value
引用:$var_name
配置文件结构:
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
|
main block
//
全局配置,对http及mail模块均有效
worker_process
//
产生多少个worker进程,一般建议和cpu个数一样
events {
...
worker_conncections 1024;
//
每个worker模型可以接受的并发数量
}
//
事件驱动的相关配置
http {
...
公共配置
server {
//
虚拟主机
...
server_name
root
//
指定根文档路径
alias
location
/url/
{
//
访问该url的专用配置
...
}
}
server {
...
}
...
};http协议相关的配置
mail {
...
};mail相关的配置
|
Nginx配置文件主要分为4部分:main(全局配置),server(主机配置),upstream(负载均衡配置),location(URL匹配特定位置) //逐层继承
main影响所有,server用于特定指定主机和端口,upstream用于负载均衡,location匹配网页位置。
server继承main,location继承server,upstream既不会继承其他设置也不会被继承。
main:全局配置:主模块执行
events:事件模块指令
http:http模块指令
===============================
1)、main段 //由核心模块引出的配置指令
http://nginx.org/en/docs/ngx_core_module.html //core指令
配置指令的类别:
正常运行必备的配置
优化性能的配置
用于调试、定位问题的配置
正常运行必备的配置:
1.user USERNAME [GROUPNAME] //指定用于运行worker进程的用户和组
例:user nginx nginx
官网--Document-->Modules reference (Core functionality)
http://nginx.org/en/docs/ngx_core_module.html#error_log
2.pid /path/to/pid_file //指定nginx进程的pid文件路径
pid /var/run/nginx.pid
3.worker_rlimit_nofile NUMBER //#指定一个nginx进程可以打开的最多文件描述符数目
性能优化的配置:
1.worker_processes NUMBER|auto //设定默认开启的worker进程数,通常应该为cpu的核心数-1,如果开启了ssl或者压缩,建议设置1.5-2倍cpu个数
2.worker_cpu_affinity //CPU绑定进程
worker_cpu_affinity cpumask ...;//cpu掩码0001,0010,0100,1000 //分别表示1,2,3,4号cpu
worker_cpu_affinity auto [cpumask]; //第几位为1,表示使用该cpu
例如:
worker_cpu_affinity 0010 0100; //绑定在2,3cpu上
ps axo pid,psr,comm
3.worker_priority NICE//指定nice优先级-20-19==100-139
用于调试、定位问题的配置
1.daemon on|off //是否以守护进程方式启动nginx,默认on到后台 ,开启守护进程回到后台运行
//只有在调试的时候,才off
2.master_process on|off;//是否以master/worker模型启动nginx进程,正常应该是on,调试时off
3.error_log file [level];//需要依赖于编译时--with-debug
error_log /var/log/nginx/error.log warn;
错误日志文件的记录方式以及日志级别
方式:file /path/to/log_file
stderr:发送到错误输出,到当前终端
syslog:server=address[,parameter=value] //发送给syslog服务器
memory:size //记录到内存中
日志级别:stderr,info,notice,warn,error,crit,alert,emerg
debug依赖于configure中的--with-debug
2)、event段
1.worker_connections 1024; //单个worker的最大并发响应数量
注:只能写在event段,默认512
注:受限于worker_rlimit_nofile //最大client连接数:worker_process * worker_conncections,
//作为反向代理时max_clients=worker_conncections*worker_process/4 //还需要考虑ulimit
2.use METHOD //指定并发链接请求处理时使用的方法,centos使用epoll
select
poll
epoll
kqueue //BSD系统中
rtsig
/dev/poll
eventport
建议:use epoll
3.accept_mutext on|off //建议开启,mutext互斥机制,临界区
on:worker进程会轮流接受新请求
4.lock_file FILE //worker使用lock实现互斥,让各worker轮流去接受请求
lock_file logs/nginx.lock
四、nginx配置之http段
默认的http段内容:
=================================================================================
1
2
3
4
5
6
7
8
9
10
11
|
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;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include
/etc/nginx/mime
.types;
default_type application
/octet-stream
;
|
==================================================================================
通用配置:
include是个主模块指令,实现对配置文件所包含的文件的设定,可以减少主配置文件的复杂度。类似于Apache中的include方法。
default_type属于HTTP核心模块指令,这里设定默认类型为二进制流,也就是当文件类型未定义时使用这种方式,例如在没有配置PHP环境时,Nginx是不予解析的,此时,用浏览器访问PHP文件就会出现下载窗口。
log_format是Nginx的HttpLog模块指令,用于指定Nginx日志的输出格式。main为此日志输出格式的名称,可以在下面的access_log指令中引用。
client_max_body_size用来设置允许客户端请求的最大的单个文件字节数。
client_header_buffer_size用于指定来自客户端请求头的headerbuffer大小。对于大多数请求,1KB的缓冲区大小已经足够,如果自定义了消息头或有更大的cookie,可以增加缓冲区大小。这里设置为32KB。
large_client_header_buffers用来指定客户端请求中较大的消息头的缓存最大数量和大小, “4”为个数,“128K”为大小,最大缓存为4个128KB。
sendfile参数用于开启高效文件传输模式。将tcp_nopush和tcp_nodely两个指令设置为on,用于防止网络阻塞。
keepalive_timeout用于设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接。
client_header_timeout用于设置客户端请求头读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。
client_body_timeout用于设置客户端请求主体读取超时时间,默认值为60。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。
send_timeout用于指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。
gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启gzip压缩,实时压缩输出数据流。
http://nginx.org/en/docs/http/ngx_http_core_module.html
1)、定义套接字功能(虚拟主机)
server标志定义虚拟主机开始;
listen用于指定虚拟主机的服务器端口;
server_name用来指定IP地址或者域名,多个域名之间用空格分开;
index用于设定访问的默认首页地址;
root指令用于指定虚拟主机的网页根目录,这个目录可以是相对路径,也可以是绝对路径;
charset用于设置网页的默认编码格式。
access_log用来指定此虚拟主机的访问日志存放路径。最后的main用于指定访问日志的输出格式。
1#.server { ... }
配置一个虚拟主机
server {
listen PORT;
server_name HOSTNAME;
root /path/to/documentroot;
...
}
2#.listen address[:port][default_server] [ssl] [backlog=number][rcvbuf=size][sndbuf=size]//
listen port [default_server] [ssl]//指定本机所有可用端口
listen unix:path [default_server] [ssl] //使用unix socket通信
套接字种类:v4,v6,unix socket //Unix socket使用的是
[backlog=number]//后援队列:人太多,等待队列排满了,靠后援队列,后援队列也满了,那就超时了
[rcvbuf=size] //接受缓冲大小
[sndbuf=size] //发送缓冲大小
default_server:默认虚拟主机//用户请求的都不匹配时的默认返回信息
ssl:限制只能通过ssl链接提供服务
3#.server_name:指定当前server的主机名;后可跟一个空白字符分隔的多个主机;
*:匹配任意长度任意字符
~:正则表达式模式匹配 ,"\d"数字0-9
假如用户请求的能够被多个server匹配到,则根据优先级,优先顺序如下
1.精确名称
2.左侧通配, *.mt.comm
3.右侧通配,www.mt.*
4.正则表达式匹配
正如:www.mt.com
1.server_name www.mt.comm;
2.server_name *.mt.comm;
3.server_name www.mt.*;
4.server_name ~^.*\.mt\..*$;
4#.tcp_nodelay on | off; //只有在长连接时启用
Nagle算法。它规定:如果包的大小满足MSS,那么可以立即发送,否则数据会被放到缓冲区,等到已经发送的包被确认了之后才能继续发送。
通过这样的规定,可以降低网络里小包的数量,从而提升网络性能。
tcp自己的优化,把多个小文件打包成一个文件发送
第一个到达的时候,太小了,等待几个小的结合到一起发,节约带宽
对keepalived模式下的链接启用tcp_nodelay选项
5#.tcp_nopush on | off;//只有在sendfile启用时才有用
开启或者关闭nginx在FreeBSD上使用TCP_NOPUSH套接字选项, 在Linux上使用TCP_CORK套接字选项。 选项仅在使用sendfile的时候才开启。
默认是关闭的
6#.sendfile on|off
在内核中直接封装响应报文,并发送,默认是关闭的,建议开启
... //等等
备注:tcp_nopush和tcp_nodelay的详细说明详见:https://www.cnblogs.com/wajika/p/6573014.html
2)、定义路径相关配置
1#.root PATH //位置http,单个server,located中仅对当前url生效,if in location
可用于server,http,location,if in location
设置web资源路径映射,用于用户请求的URL所对应的本地文件系统上的文档目录路径
2#.location
location [ = | ~ | ~* | ^~ |@ ] uri { ... } //优先级
匹配模式:
=:精确匹配
~:正则表达式模式匹配,区分字符大小写
~*:正则表达式模式匹配,不区分字符大小写
^~:锚定行首 //对开头前的uri匹配
@:是用来定义“Named Location ”的(可以理解为独立于“普通location”和“正则location”之外的第三种类型),这种“Named Location ”不是用来处理普通的HTTP 请求的,它是专门用来处理“内部重定向(internally redirected )”请求的。
注意:这里说的“内部重定向(internally redirected )”是不需要跟浏览器交互的,纯粹是服务端的一个转发行为。
匹配优先级:=,^~,~*,~,不带符号 //从大到小
location @name { ... }
location可以放在server内部,也可放在location内部
根据用户请求的URI来匹配定义的location,匹配到时,此请求将被响应的location中所配置的块所响应
示例1:
location ~*\.txt {
gzip on;
}
server {
...
location {
...
}
location {
...
}
}
示例2:
location ~ .*\.(gif|jpg|jpeg|png|bmgf|swf)$ { //区分大小写
root /web/www/picture;
expires 30d; //指定静态文件的过期时间为30天
}
示例3:
location ~ .*.jsp$ {
index index.jsp;
proxy_pass http://localhost:8080;
}
示例4:
location ~ ^/(upload|html)/ {
root /web/www;
expires 30d;
}
将upload和html下的所有文件都交给Nginx来处理。
//假如有多个location匹配到了
3#.alias path: //定义路径别名
只能用在location中
location /i/ {
alias /data/w3/images/;
}
注意:
alias指令,给定的路径对应于location中的/uri/后的这个url
注:附件2
4#.index index.html //设置默认主页
http,server,location中都可以定义
5#.自定义错误页面 //根据用户请求的资源的http响应码
定义在:http,server,location中
error_page code ... [=[response]] uri;
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
error_page 404 =200 /empty.gif; //重定向404响应码为200
error_page
6#.try_file //应用于server,location,
try_files file ... uri; //用户请求的页面不存在,使用的响应文件,依次查找,都没有,就用uri
try_files file ... =code;
location /images/ {
try_files $uri /images/default.gif;
}
3)、定义客户端请求的相关配置
1#.keepalive相关,应用在http,server,location
keepalive_disable none|browser //关闭对哪些浏览器的keepalive
例如:keepalive_disable msie6 //msie6不支持长连接
2#.keepalive_requests number //一次长连接所允许请求资源的最大数量
3#.keepalive_timeout timeout [header_timeout]; //超时时间,默认75s
keepalive_timeout 75s //默认
4#.send_timeout 60s //向客户端发送响应报文的超时时长;特别地,是指两次写操作之间的间隔时长
5#.client_body_buffer_size size; //接受客户端请求报文的body部分的缓冲区大小,默认为16k,超出此大小时,其将被暂存到磁盘上
client_body_buffer_size 8k|16k;
6#.client_body_temp_path path [level1 [level2 [level3]]];
设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量
例如/var/tmp/body/1,2,3子目录, 分级存储,
level1,创建多少个1级子目录,多少个2级子目录,多少个3级子目录
/var/tmp/body 2 1 //创建一级子目录256个,每个一级目录创建16个子目录
2:16进制表示从00-ff,2个十六进制字符来创建一级子目录,1个16进制字符来创建二级子目录
2个16进制表示范围:256
client_body_temp_path /spool/nginx/client_temp 1 2;
6#.client_body_in_file_only on | clean | off;
7#.client_body_in_single_buffer on | off;
8#.
9#.client_body_timeout time;
10#.client_header_buffer_size size;
11#.client_header_timeout time;
12#.client_max_body_size size;
4)、对客户的请求进行限制的配置
1#.limit_rate rate //限制响应给客户端每s响应的速率,单位: bytes/second默认是 0:不做限制
location /download/ {
root /web/htdocs;
limit_rate 20;
}
使用dd命令创建测试文件
wget去下载
2#.limit_execpt method...{...} //使用范围location
limit_execpt GET POST { //只允许该主机可以使用GET,POST之外的其他方法
allow 192.168.1.1/32; //GET方法是大家都可以使用
deny all;
}
curl -X ///使用自定义方法
5)、文件操作优化的配置
1#.aio on|off|threads[=pool] //异步IO,定义为http,server,location中
location /video/ { //线程池不指定,用多少,启用多少
aio on;
oputput_bufffers 64k;
}
2#.directio size|off //直接io,http,server,location,//数据不再内存中保留,直接写入到disk
3#.open_file_cache off; //是否缓存,缓存文件的元数据,并不是文件的内容
open_file_cache max=N [inactive=time] //缓存多少个文件的信息,失效时间20s
//当条目满载的时候,使用LRU最近最少使用算法剔除那些不经常使用的
//inactive:多长时间内没有被访问,就定为超时,剔除
nginx可以缓存以下三种信息:
1.文件的描述符,文件大小,和最近一次修改的时间
2.打开的目录的结构,
3.没有找到的文件,或者没有权限访问的文件的相关信息
open_file_cache max=1000 inactive=20s
4#.open_file_cache_errors on | off; //是否缓存查找时发生错误的文件的相关信息
5#.open_file_cache_min_uses number; //open_file_cache指定的inactive参数定义的时长内,至少被命中此处指定的次数,方可不被归类为inactive
6#.open_file_cache_valid time //valid:合法的,每隔多长时间检查一下缓存是否失效,默认60s
五、其他模块
1)、ngx_http_access_module
http://nginx.org/en/docs/http/ngx_http_core_module.html
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
allow address | CIDR | unix: | all;
应用Context:http, server, location, limit_except
2)、ngx_http_auth_basic_module
location /admin/ {
auth_basic "closed site";
auth_basic_user_file conf/htpasswd;
}
Syntax: auth_basic string | off;
Default:
auth_basic off;
Context: http, server, location, limit_except
使用openpasswd或者htpasswd生成
yum -y install httpd
htpasswd -c -m /etc/nginx/.nginxpasswd tom //-d crypt加密
htpaswwd -m /etc/nginx/.nginxpasswd wolf
文件格式:
name:passwd:comment
vim /etc/nginx/nginx.conf
http {
server {
server_name www.mt.com;
root /web/www;
listen 80;
location /admin/ {
auth_basic "Admin Area.";
auth_basic_user_file /etc/nginx/.ngpasswd;
}
}
//注:location只能在server内部,否则会报错
3)、ngx_http_stub_status_module //状态页面
nginx状态输出:以后做监控的时候会用到
4)、ngx_http_referer_module //引用参考,从哪里获取到的数据
valid_referers none blocked server_names
*.example.com example.* www.example.org/galleries/
~\.google\.;
if ($invalid_referer) { //不被valid_referers匹配到的都是invalid_refer变量的内容
return 403;
}
valid_referers none | blocked | server_names | string
//定义合法的
none:请求报文中首部没有refer首部
blocked:请求报文refer首部没有值
server_names:给定一个服务器名称,来自于该服务器的都认为是合法的
string:
直接字符串,可以使用*作为通配符;
指定正则表达式匹配到的字符串;要使用~开头;
valid_referers none blocked server_names *.mt.com *.mt.* ~\.mt\.
注:该模块主要用于防盗链
六、实验
实验一:开启status页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
http {
server {
server_name www.mt.com;
root
/web/www
;
listen 80;
location
/admin/
{
auth_basic
"Admin Area."
;
auth_basic_user_file
/etc/nginx/
.ngpasswd;
}
location
/status
{
stub_status;
}
}
}
|
http://192.168.4.118/status
Active connections: 2 //活动连接,正在处于活动状态的客户端连接请求的数量
server accepts handled requests //以前的统计数据
13 13 11
Reading: 0 Writing: 1 Waiting: 1 //正在进行的请求
accpet:已经接受的客户端连接总数 //总共处理了的连接数
handled:已经处理完成的客户端连接总数 //成功创建握手的次数
Waiting:共处理的总请求数
Reading:处于读取client请求报文首部的数量
Writing:处于向客户端发送响应报文过程中的连接数
Waiting:处于等待客户端发送请求的空闲进程数,太多,建议调低keepalive值 ////开启 keep-alive 的情况下,这个值等于 active – (reading+writing), 意思就是 Nginx 已经处理完正在等候下一次请求指令的驻留连接。所以,在访问效率高,请求很快被处理完毕的情况下,Waiting数比较多是正常的.如果reading +writing数较多,则说明并发访问量非常大,正在处理过程中。
注:假如无法访问,可以尝试修改server_name为ip地址
实验二:虚拟主机实现
1.vim /etc/hosts //windows也要修改hosts文件
192.168.4.118 www.mt.com web.mt.com
2.vim /etc/nginx/nginx.conf //或者vim /etc/nginx/conf.d/vhosts.conf新建配置文件
server {
listen 80;
server_name www.mt.com;
root /web/www;
}
server {
listen 80;
server_name web.mt.com;
root /web/web;
}
//注:只能在httpd { } 内部
mkdir /web/{web,www} -pv
echo "<h1> web </h1>" > /web/web/index.html
echo "<h1> www </h1>" > /web/www/index.html
nginx -t
nginx -s reload
注意:
1.基于port的虚拟主机
listen指令要使用不同的端口
2.基于hostname的虚拟主机
server_name指向不同的主机名
3.基于ip的虚拟主机
listen IP:PORT
七、其他
1、location匹配顺序
location开始:
附件1:location匹配顺序
//:=,^~,~*,~,不带符号 //从大到小
//等于,左半,区分大消息的正则表达式,正则表达式[不区分],不带符号
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
location = / {
//
精确匹配
[ configuration A ]
}
location / {
//
什么都没有
[ configuration B ]
}
location
/documents/
{
//
什么都没有,B和C优先级一样,但是C更精确
[ configuration C ]
}
location ^~
/images/
{
//
锚定行首
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
//
有空格,正则表达式不区分大小写
[ configuration E ]
}
|
对www.mt.com 的请求会匹配到A,
对www.mt.com/index.html的请求会匹配到B
对www.mt.com/documents/document.html会匹配到C
对www.mt.com/images/1.gif会匹配到D
对www.mt.com/documents/1.jpg会匹配到E //C的优先级低于E
2、root和alias的对应关系
http://www.mt.com/bbs/a.jpg
方法1:
location /bbs/ {
alias /web/forum/;
}
访问的是/web/forum/a.jpg
方法2:
location /bbs/ {
root /web/forum/;
}
访问的是:/web/forum/bbs/a.jpg
root指令:相当于 /bbs/ 最左侧的 "/"
alias指令:相当于 /bbs/ 最右侧的 "/"
参考博客:
http://blog.51cto.com/freeloda/1288553
http://www.nginx.cn/doc/
http://nginx.org/en/docs/
本文转自MT_IT51CTO博客,原文链接:http://blog.51cto.com/hmtk520/2067542,如需转载请自行联系原作者