Nginx配置指令(一)

Nginx配置指令(一)

main配置段常见的配置指令:

分类:
    正常运行必备的配置
    优化性能相关的配置
    用于调试及定位问题相关的配置
    事件驱动相关的配置

正常运行必备的配置:

1、user

1
2
3
4
5
6
Syntax: user user [group];
Default: user nobody nobody;
Context: main
Defines user and group credentials used by worker processes. If group is omitted,
a group whose name equals that of user is used.

2、pid;

指定存储nginx主进程进程号码的文件路径;

1
2
3
4
5
Syntax: pid file;
Default: pid nginx.pid;
Context: main
Defines a file that will store the process ID of the main process.

3、include file | mask;

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

1
2
3
4
5
6
Syntax: include file | mask;
Default: —
Context: any
Includes another file, or files matching the specified mask, into configuration.
Included files should consist of syntactically correct directives and blocks.

4、load_module file;

指明要装载的动态模块;

1
2
3
4
5
6
7
8
9
10
11
Syntax: load_module file;
Default: —
Context: main
This directive appeared in version 1.9.11.
Loads a dynamic module.
Example:
load_module modules/ngx_mail_module.so;

性能优化相关的配置:

1、worker_processes number | auto;

worker: 进程的数量;通常应该等于小于当前主机的cpu的物理核心数;

auto:当前主机物理CPU核心数;

1
2
3
4
5
6
7
8
9
10
11
Syntax: worker_processes number | auto;
Default: worker_processes 1;
Context: main
Defines the number of worker processes.
The optimal value depends on many factors including (but not limited to) the number of CPU cores,
the number of hard disk drives that store data, and load pattern. When one is in doubt, setting it to
the number of available CPU cores would be a good start (the value “auto” will try to autodetect it).
The auto parameter is supported starting from versions 1.3.8 and 1.2.5.

2、worker_cpu_affinity cpumask …;

把进程与CPU绑定;

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
Syntax: worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default: —
Context: main
Binds worker processes to the sets of CPUs. Each CPU set is represented by a bitmask of allowed CPUs.
There should be a separate set defined for each of the worker processes. By default, worker processes
are not bound to any specific CPUs.
For example,
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
binds each worker process to a separate CPU, while
worker_processes 2;
worker_cpu_affinity 0101 1010;
binds the first worker process to CPU0/CPU2, and the second worker process to CPU1/CPU3.
The second example is suitable for hyper-threading.
The special value auto (1.9.10) allows binding worker processes automatically to available CPUs:
worker_processes auto;
worker_cpu_affinity auto;
The optional mask parameter can be used to limit the CPUs available for automatic binding:
worker_cpu_affinity auto 01010101;
The directive is only available on FreeBSD and Linux.

3、worker_priority number;

指定worker进程的nice值,设定worker进程优先级;[-20,20]
默认都为0

1
2
3
4
5
6
7
8
9
10
Syntax: worker_priority number;
Default: worker_priority 0;
Context: main
Defines the scheduling priority for worker processes like it is done by the nice command:
a negative number means higher priority. Allowed range normally varies from -20 to 20.
Example:
worker_priority -10;

4、worker_rlimit_nofile number;

worker进程所能够打开的文件数量上限;

1
2
3
4
5
6
Syntax: worker_rlimit_nofile number;
Default: —
Context: main
Changes the limit on the maximum number of open files (RLIMIT_NOFILE) for worker
processes. Used to increase the limit without restarting the main process.

调试、定位问题:

1、daemon on|off;

是否以守护进程方式运行Nignx;

1
2
3
4
5
Syntax: daemon on | off;
Default: daemon on;
Context: main
Determines whether nginx should become a daemon. Mainly used during development.

2、master_process on|off;

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

1
2
3
4
5
6
Syntax: master_process on | off;
Default: master_process on;
Context: main
Determines whether worker processes are started. This directive is intended for
nginx developers.

3、error_log file [level];

错误日志文件;

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
Syntax: error_log file [level];
Default: error_log logs/error.log error;
Context: main, http, mail, stream, server, location
Configures logging. Several logs can be specified on the same level (1.5.2). If on the
main configuration level writing a log to a file is not explicitly defined, the default
file will be used.
The first parameter defines a file that will store the log. The special value stderr
selects the standard error file. Logging to syslog can be configured by specifying the
“syslog:” prefix. Logging to a cyclic memory buffer can be configured by specifying the
“memory:” prefix and buffer size, and is generally used for debugging (1.7.11).
The second parameter determines the level of logging, and can be one of the following:
debug, info, notice, warn, error, crit, alert, or emerg. Log levels above are listed in
the order of increasing severity. Setting a certain log level will cause all messages of
the specified and more severe log levels to be logged. For example, the default level
error will cause error, crit, alert, and emerg messages to be logged. If this parameter
is omitted then error is used.
For debug logging to work, nginx needs to be built with --with-debug, see “A
debugging log”.
The directive can be specified on the stream level starting from version 1.7.11, and
on the mail level starting from version 1.9.0.

ps:以上配置适用于开发测试环节

事件驱动相关的配置:

放在events配置块内;

1、worker_connections number;

每个worker进程所能够打开的最大并发连接数数量;

1
2
3
4
5
6
7
8
9
10
Syntax: worker_connections number;
Default: worker_connections 512;
Context: events
Sets the maximum number of simultaneous connections that can be opened by a worker process.
It should be kept in mind that this number includes all connections (e.g. connections with proxied
servers, among others), not only connections with clients. Another consideration is that the actual
number of simultaneous connections cannot exceed the current limit on the maximum number of open files,
which can be changed by worker_rlimit_nofile.

2、use method;

指明并发连接请求的处理方法;

1
2
3
4
5
6
Syntax: use method;
Default: —
Context: events
Specifies the connection processing method to use. There is normally no need to specify it explicitly,
because nginx will by default use the most efficient method.

use epoll;

3、accept_mutex on | off;

处理新的连接请求的方法;
on意味着由各worker轮流处理新请求;
Off意味着每个新请求的到达都会通知所有的worker进程;

1
2
3
4
5
6
7
8
9
10
11
12
Syntax: accept_mutex on | off;
Default: accept_mutex off;
Context: events
If accept_mutex is enabled, worker processes will accept new connections by turn. Otherwise, all worker
processes will be notified about new connections, and if volume of new connections is low, some of the
worker processes may just waste system resources.
There is no need to enable accept_mutex on systems that support the EPOLLEXCLUSIVE flag (1.11.3) or
when using reuseport.
Prior to version 1.11.3, the default value was on.

http协议的相关配置:

放在HTTP配置块内;

配置在HTTP内server外,配置对所有server生效。

与套接字相关的配置:

1. server

配置一个虚拟主机

1
2
3
4
5
6
7
8
9
Syntax: server { ... }
Default: —
Context: http
Sets configuration for a virtual server. There is no clear separation between IP-based
(based on the IP address) and name-based (based on the “Host” request header field)
virtual servers. Instead, the listen directives describe all addresses and ports that
should accept connections for the server, and the server_name directive lists all server names.
Example configurations are provided in the “How nginx processes a request” document.

2. listen

监听的端口

格式有三种,常用前两种;

此处只介绍,格式用法,详细说明请查看:http://nginx.org/en/docs/http/ngx_http_core_module.html#listen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Syntax: listen address[:port] [default_server] [ssl] [http2 | spdy] [proxy_protocol]
[setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size]
[sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|
[keepidle]:[keepintvl]:[keepcnt]];
listen port [default_server] [ssl] [http2 | spdy] [proxy_protocol]
[setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size]
[sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
listen unix:path [default_server] [ssl] [http2 | spdy] [proxy_protocol] [backlog=number]
[rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default: listen *:80 | *:8000;
Context: server
Sets the address and port for IP, or the path for a UNIX-domain socket on which the
server will accept requests. Both address and port, or only address or only port can be specified.
An address may also be a hostname, for example:
listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

3. server_name

主机名

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

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

server_name *.test.com 

或 

server_name www.test.*

支持~起始的字符做正则表达式模式匹配;

server_name ~^www\d+\.test\.com$

匹配机制:

(1) 首先是字符串精确匹配;
(2) 左侧*通配符;
(3) 右侧*通配符;
(4) 正则表达式;

此处只介绍,格式用法,详细说明请查看:http://nginx.org/en/docs/http/ngx_http_core_module.html#server_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
Syntax: server_name name ...;
Default: server_name "";
Context: server
Sets names of a virtual server, for example:
server {
server_name example.com www.example.com;
}
The first name becomes the primary server name.
Server names can include an asterisk (“*”) replacing the first or last part of a name:
server {
server_name example.com *.example.com www.example.*;
}
Such names are called wildcard names.
The first two of the names mentioned above can be combined in one:
server {
server_name .example.com;

4. sendfile on | off;

关于sendfile的具体介绍:http://www.oschina.net/question/54100_33185

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Syntax: sendfile on | off;
Default: sendfile off;
Context: http, server, location, if in location
Enables or disables the use of sendfile().
Starting from nginx 0.8.12 and FreeBSD 5.2.1, aio can be used to pre-load data for sendfile():
location /video/ {
sendfile on;
tcp_nopush on;
aio on;
}
In this configuration, sendfile() is called with the SF_NODISKIO flag which causes it not to block on
disk I/O, but, instead, report back that the data are not in memory. nginx then initiates an asynchronous
data load by reading one byte. On the first read, the FreeBSD kernel loads the first 128K bytes of a file
into memory, although next reads will only load data in 16K chunks. This can be changed using the read_ahead directive.
Before version 1.7.11, pre-loading could be enabled with aio sendfile;.

5. tcp_nodelay on | off;

开启或关闭nginx使用TCP_NODELAY选项的功能。 这个选项仅在将连接转变为长连接的时候才被启用。

1
2
3
4
5
6
Syntax: tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location
Enables or disables the use of the TCP_NODELAY option.
The option is enabled only when a connection is transitioned into the keep-alive state.

6. tcp_nopush on | off;

开启或者关闭nginx在FreeBSD上使用TCP_NOPUSH套接字选项, 在Linux上使用TCP_CORK套接字选项。
选项仅在使用sendfile的时候才开启。 开启此选项允许在Linux和FreeBSD 4.*上将响应头和正文的开始部分一起发送;一次性发送整个文件。

1
2
3
4
5
6
7
8
Syntax: tcp_nopush on | off;
Default: tcp_nopush off;
Context: http, server, location
Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows
sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*;
sending a file in full packets.

详细介绍sendfile、tcp_nodelay、tcp_nopush之间的关系请参考:http://www.cnblogs.com/wajika/p/6573014.html

定义路径的相关配置:

1. root

设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
Sets the root directory for requests. For example, with the following configuration
location /i/ {
root /data/w3;
}
The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request.
The path value can contain variables, except $document_root and $realpath_root.
A path to the file is constructed by merely adding a URI to the value of the root directive.
If a URI has to be modified, the alias directive should be used.

2. location

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

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
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
=:对URI做精确匹配;
~:对URI做正则表达式模式匹配,区分字符大小写;
~*:对URI做正则表达式模式匹配,不区分字符大小写;
^~:对URI的左半部分做匹配检查,不区分字符大小写;
不带符号:匹配起始于此uri的所有的url;
匹配优先级:=, ^~, ~/~*,不带符号;
Let’s illustrate the above by an example:
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
The “/” request will match configuration A,
the “/index.html” request will match configuration B,
the “/documents/document.html” request will match configuration C,
the “/images/1.gif” request will match configuration D,
the “/documents/1.jpg” request will match configuration E.

3. alias

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

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

(a) root,给定的路径对应于location中的/uri/左侧的/;
(b) alias,给定的路径对应于location中的/uri/右侧的/;
1
2
3
4
5
6
7
8
9
10
11
12
Syntax: alias path;
Default: —
Context: location
location ~* /images/ {
root /data/pictures/;
在/data/pictures目录下找image/s目录下的文件
}
location ^~ /images/ {
alias /data/pictures/;
别名,访问/images等于访问/date/pictures/
}

4. index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Syntax: index file ...;
Default: index index.html;
Context: http, server, location
Defines files that will be used as an index. The file name can contain variables. Files are checked in the specified order.
The last element of the list can be a file with an absolute path. Example:
index index.$geo.html index.0.html /index.html;
It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location. For example, with the following configuration:
location = / {
index index.html;
}
location / {
...
}
a “/” request will actually be processed in the second location as “/index.html”.

5. error_page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Syntax: error_page code ... [=[response]] uri;
Default: —
Context: http, server, location, if in location
Defines the URI that will be shown for the specified errors. A uri value can contain variables.
Example:
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
error_page 404 =200 /notfound.html;
location = /notfound.html {
root /data/nginx/error_pages;
}
#自定义error页,并且也能更改返回状态码。
<% if (theme.canvas_nest) { %> <% } %> s