Nginx配置文件(nginx.conf)详解
目录
转载请备注来源: 《Nginx配置文件(nginx.conf)详解》 | shuwoom.com
本文介绍
本文主要介绍nginx.conf配置文件的各个常用配置项的使用。
nginx.conf配置文件详解
Nginx服务启动时会读取配置文件,后续行为则根据配置文件中的指令进行。
Nginx配置文件是以块block形式组织的,每个block都是一个名字和一对大括号{}表示组成。
block分为几个层级,整个配置文件是main层级,即最大的层级,在main之下还有event、http等层级,而http中又包含server block,server block种包含location block。块和块之间可以层层嵌套,内层块继承外层块。
Nginx配置文件通常的结构如下图:

# worker进程数量 worker_processes 1; #绑定 Nginx worker 进程到指定的 CPU 内核 #语法:worker_cpu_affinity cpumask [cpumask...] # # 日志设置 # 错误级别有: 有: debug info notice warn error crit alert emerg,从左只有级别增加 # 只输出级别大于或等于已设定的级别的日志 # 路径 错误级别 error_log logs/error.log error; # 用于nginx崩溃报错是排障调试 # 限制 coredump 核心转储文件的大小 # 语法:worker_rlimit_core size; #指定 coredump 文件的生成目录 #语法:working_directory path; events { # 每个worker进行的最大连接数 worker_connections 1024; } http { include mime.types; 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; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } # 根据HTTP返回码重定向页面 error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
参考:https://www.kancloud.cn/digest/understandingnginx/202587
Nginx的配置可以大致分为以下四类:
- 用于调试和定位的配置项
- 正常运行的配置项
- 优化性能的配置项
- 事件类配置项
下面我们一个分开来讲解:
官方原文参考:http://nginx.org/en/docs/ngx_core_module.html
nginx.conf用于调试和定位的配置项
daemon
是否以守护进程的方式运行Nginx
Syntax: | daemon on | off; |
---|---|
Default: | daemon on; |
Context: | main |
master_process
master/worker工作方式。
Syntax: | master_process on | off; |
---|---|
Default: | master_process on; |
Context: | main |
error_log
Syntax: | error_log file [level]; |
---|---|
Default: | error_log logs/error.log error; |
Context: | main , http , mail , stream , server , location |
level级别: debug info notice warn error crit alert emerg
从左至右级别增大;若设定一个级别后,则在输出的日志文件中只输出级别大于或等于已设定的级别
debug_points
这个设置是用来跟踪调试Nginx的
Syntax: | debug_points abort | stop; |
---|---|
Default: | — |
Context: | main |
debug_connection
仅对指定的客户端输出debug级别的日志
Syntax: | debug_connection address | CIDR | unix:; |
---|---|
Default: | — |
Context: | events |
例如:
events { debug_connection 127.0.0.1; debug_connection localhost; debug_connection 192.0.2.0/24; debug_connection ::1; debug_connection 2001:0db8::/32; debug_connection unix:; ... }
注意:要启用这个功能,在编译nginx时需要加上--with-debug。
worker_rlimit_core
限制coredump核心转储文件的大小
Syntax: | worker_rlimit_core size; |
---|---|
Default: | — |
Context: | main |
working_directory
指定coredump文件的目录生成地址
Syntax: | working_directory directory; |
---|---|
Default: | — |
Context: | main |
nginx.conf正常运行的配置项
env
定义环境变量
Syntax: | env variable[=value]; |
---|---|
Default: | env TZ; |
Context: | main |
例如:
env MALLOC_OPTIONS; env PERL5LIB=/data/site/modules; env OPENSSL_ALLOW_PROXY_CERTS=1;
include
嵌入其他配置文件
Syntax: | include file | mask; |
---|---|
Default: | — |
Context: | any |
例如:
include mime.types; include vhosts/*.conf;
pid
指定pid文件路径,该配置项保存master进程ID的pid文件存放路径
Syntax: | pid file; |
---|---|
Default: | pid logs/nginx.pid; |
Context: | main |
user
设置nginx worker运行的用户和用户组
Syntax: | user user [group]; |
---|---|
Default: | user nobody nobody; |
Context: | main |
worker_rlimit_nofile
指定Nginx Worker进程可打开最大句柄个数。这里建议保持跟ulimit -n一致。
查看linux系统下,所有进程允许打开的最大fd数量:
[root@VM_16_4_centos ~]# cat /proc/sys/fs/file-max 791773
查看linux系统下,所有进程已经打开的fd数量及允许的最大数量:
[root@VM_16_4_centos ~]# cat /proc/sys/fs/file-nr 4832 0 791773
查看单个进程允许打开的最大fd数量:
[root@VM_16_4_centos ~]# ulimit -n 100001
查看单个进程已经打开的fd:
ls -l /proc/进程id/fd/
例如,查看nginx进程的fd情况:
[root@VM_16_17_centos ~]# ps -ef|grep nginx root 10196 10174 0 09:32 pts/0 00:00:00 grep nginx root 14665 1 0 Jun19 ? 00:00:00 nginx: master process /usr/local/services/nginx-1.0/sbin/nginx -c /usr/local/services/nginx-1.0/conf/nginx.conf nginx 14666 14665 0 Jun19 ? 00:09:10 nginx: worker process nginx 14667 14665 0 Jun19 ? 00:13:39 nginx: worker process nginx 14668 14665 0 Jun19 ? 00:21:32 nginx: worker process nginx 14670 14665 0 Jun19 ? 00:22:32 nginx: worker process
[root@VM_16_17_centos ~]# ps -ef|grep nginx root 10196 10174 0 09:32 pts/0 00:00:00 grep nginx root 14665 1 0 Jun19 ? 00:00:00 nginx: master process /usr/local/services/nginx-1.0/sbin/nginx -c /usr/local/services/nginx-1.0/conf/nginx.conf nginx 14666 14665 0 Jun19 ? 00:09:10 nginx: worker process nginx 14667 14665 0 Jun19 ? 00:13:39 nginx: worker process nginx 14668 14665 0 Jun19 ? 00:21:32 nginx: worker process nginx 14670 14665 0 Jun19 ? 00:22:32 nginx: worker process [root@VM_16_17_centos ~]# ls -l /proc/14666/fd/ total 0 lrwx------ 1 nginx nginx 64 Jul 17 09:18 0 -> /dev/null lrwx------ 1 nginx nginx 64 Jul 17 09:18 1 -> /dev/null lrwx------ 1 nginx nginx 64 Jul 17 09:18 10 -> socket:[659055045] lrwx------ 1 nginx nginx 64 Jul 17 09:18 11 -> [eventpoll] lrwx------ 1 nginx nginx 64 Jul 17 09:18 12 -> [eventfd] lrwx------ 1 nginx nginx 64 Jul 17 09:18 13 -> socket:[659055048] lrwx------ 1 nginx nginx 64 Jul 17 09:18 14 -> socket:[659055052] l-wx------ 1 nginx nginx 64 Jul 17 09:18 2 -> /usr/local/services/nginx-1.0/logs/error.log lrwx------ 1 nginx nginx 64 Jul 17 09:18 3 -> socket:[659055046] l-wx------ 1 nginx nginx 64 Jul 17 09:18 4 -> /data/log/nginx-1.0/error.log l-wx------ 1 nginx nginx 64 Jul 17 09:18 5 -> /usr/local/services/nginx-1.0/logs/error.log lrwx------ 1 nginx nginx 64 Jul 17 09:18 6 -> socket:[659055038] lrwx------ 1 nginx nginx 64 Jul 17 09:18 7 -> socket:[659055039] lrwx------ 1 nginx nginx 64 Jul 17 09:18 8 -> socket:[659055040] lrwx------ 1 nginx nginx 64 Jul 17 09:18 9 -> socket:[659055041]
Syntax: | worker_rlimit_nofile number; |
---|---|
Default: | — |
Context: | main |
nginx.conf优化性能配置项
worker_processes
nginx worker进程个数
Syntax: | worker_processes number | auto; |
---|---|
Default: | worker_processes 1; |
Context: | main |
其中auto选项允许worker进程自动根据CPU核数进行设置,一般这个设置为CPU核数。
worker_cpu_affinity
绑定Nginx worker进程到指定的内核
Syntax: | worker_cpu_affinity cpumask ...; worker_cpu_affinity auto [cpumask]; |
---|---|
Default: | — |
Context: | main |
其中auto选项可以让worker进程自动绑定可用的CPU核
例如:
worker_processes 4; worker_cpu_affinity 0001 0010 0100 1000;
或者,给第一个worker进程分配CPU0/CPU2,第二个worker进程分配CPU1/CPU3
worker_processes 2; worker_cpu_affinity 0101 1010;
ssl_engine
SSL硬件加速
Syntax: | ssl_engine device; |
---|---|
Default: | — |
Context: | main |
timer_resolution_interval
系统调用gettimeofday的执行频率
Syntax: | timer_resolution interval; |
---|---|
Default: | — |
Context: | main |
worker_priority
设置Nginx worker进程优先级,设置范围从-20 到20,数值越小,权限越高。这种一般在服务器上还有其他服务并存的情况下设置。
Syntax: | worker_priority number; |
---|---|
Default: | worker_priority 0; |
Context: | main |
pcre_jit
在解析配置文件时对正则表达式启用或禁用实时编译(PCREJIT,即just in time compilation),PCRE JIT能显著提升正则表达式的处理速度。
JIT依赖PCRE库8.20以后版本,并且在编译时需要指定--enable-jit参数。也可以将PCRE库作为nginx的模块编译安装(编译nginx指定--with-pcre=参数),并在编译时指定--with-pcre-jit参数启用JIT功能。
Syntax: | pcre_jit on | off; |
---|---|
Default: | pcre_jit off; |
Context: | main |
thread_pool
采用asynchronous file I/O (AIO),多线程读写不锁worker。Nginx 1.7.11以上的版本可使用,加 --with-threads
配置参数编译。
Syntax: | thread_pool name threads=number [max_queue=number]; |
---|---|
Default: | thread_pool default threads=32 max_queue=65536; |
Context: | main |
例如:
thread_pool one threads=128 max_queue=0; thread_pool two threads=32; http { server { location /one { aio threads=one; } location /two { aio threads=two; } } … }
详细的性能分析文章参考:https://www.infoq.cn/article/thread-pools-boost-performance-9x
nginx.conf事件类配置项
accept_mutex
是否打开accept锁。如果启用了accept锁,则worker进程会以串行的方式来处理新连接,其中一个worker进程会被唤醒,其他worker进程处于休眠状态。如果不打开,则所有worker进程都会被唤醒,不过这个时候只有一个worker进程可以获取连接,其他worker进程会重新进入休眠状态。
开启accept_mutext可以让worker进程处理请求分配更均匀些。
Syntax: | accept_mutex on | off; |
---|---|
Default: | accept_mutex off; |
Context: | events |
参考:https://www.cnblogs.com/sxhlinux/p/6254396.html
lock_file
lock文件的路径。nginx通过锁机制来实现accept_mutex,并通过序列化的方法来实现对共享内存的访问。
Syntax: | lock_file file; |
---|---|
Default: | lock_file logs/nginx.lock; |
Context: | main |
accept_mutex_deplay
使用accept锁喉真正建立连接之间的延迟时间。
Syntax: | accept_mutex_delay time; |
---|---|
Default: | accept_mutex_delay 500ms; |
Context: | events |
multi_accept
批量建立新连接。如果multi_accept没启用,则worker进程每次只会接受一个连接。如果启用,则worker进程会依次接收所有新连接。
Syntax: | multi_accept on | off; |
---|---|
Default: | multi_accept off; |
Context: | events |
use
选择事件模型,包括selcet,poll,kqueue,/dev/poll,epoll,eventport。这个选项没必要设置,因为nginx会自动选择最有效的方法作为默认项。
Syntax: | use method; |
---|---|
Default: | — |
Context: | events |
- worker_connections
每个worker进程最大的连接数,理论上来说每台nginx服务器的最大连接数为:worker_processes worker_connections。注意这个数值不能大过worker进程最大的open files数量,这个可以通过worker_rlimit_nofile配置项修改。
Syntax: | worker_connections number; |
---|---|
Default: | worker_connections 512; |
Context: | events |
Nginx Http核心模块配置
参考官方文档:http://nginx.org/en/docs/http/ngx_http_core_module.html
keeplive_timeout
http连接超时时间,该参数不能设置过大,否则会导致很多无效的http连接占用nginx资源。
Syntax: | keepalive_timeout timeout [header_timeout]; |
---|---|
Default: | keepalive_timeout 75s; |
Context: | http , server , location |
client_header_buffer_size
客户端请求头部的缓冲区大小。对于大部分请求来说,1k是足够的,但是如果一些请求包含很长的cookie等,1k大小就可能不够。如果该值无法适用于请求头部的大小,则large_client_header_buffers这个参数可以发挥作用。
Syntax: | client_header_buffer_size size; |
---|---|
Default: | client_header_buffer_size 1k; |
Context: | http , server |
open_file_cache
这个参数会给打开的文件指定缓存。max是指定缓存数量,inactive是指经过多长时间文件没别请求后删除缓存。
Syntax: | open_file_cache off; open_file_cache max=N [inactive=time]; |
---|---|
Default: | open_file_cache off; |
Context: | http , server , location |
例如:
open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;
open_file_cache_valid
指定多长时间检查一次缓存的有效信息
Syntax: | open_file_cache_valid time; |
---|---|
Default: | open_file_cache_valid 60s; |
Context: | http , server , location |
open_file_cache_min_uses
指定时间内文件的最少使用次数,如果低于这个数字,则缓存文件会被移除。
Syntax: | open_file_cache_min_uses number; |
---|---|
Default: | open_file_cache_min_uses 1; |
Context: | http , server , location |
server_tokens
是否隐藏响应头和错误页中有关nginx版本号的信息。
Syntax: | server_tokens on | off | build | string; |
---|---|
Default: | server_tokens on; |
Context: | http , server , location |
sendfile
sendfile也就是网上说的零拷贝技术。sendfile要比组合read和write更加高效,其拷贝是在内核层完成。
Syntax: | sendfile on | off; |
---|---|
Default: | sendfile off; |
Context: | http , server , location , if in location |

tcp_nopush
这个参数只有在启用sendfile的时候才能启用。启用这个参数后,数据报不会马上发送出去,等到数据包最大时,一次性的传输出去,这样有助于解决网络堵塞。
Syntax: | tcp_nopush on | off; |
---|---|
Default: | tcp_nopush off; |
Context: | http , server , location |
tcp_nodelay
当连接状态是keep-alive状态时,将会启用这个选项。
Syntax: | tcp_nodelay on | off; |
---|---|
Default: | tcp_nodelay on; |
Context: | http , server , location |
location的正则匹配规则
Syntax: | location [ = | ~ | ~* | ^~ ] uri* { ... } location @*name* { ... } |
---|---|
Default: | — |
Context: | server , location |
location有两种表达形式:
(1)前缀字符串
=: 精确匹配,只有请求的url路径与后面的字符串完全相等时,才会命中
^~: 匹配上后则不再进行正则表达式匹配
注意,这里两个匹配上之后就不会再往下匹配。
(2)正则表达式
~: 大小写敏感的正则匹配
~*: 忽略大小写的正则匹配

我们用下面的例子来举例说明:
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { [ configuration E ] }
请求/精准匹配A,不用再往下查找。
请求/index.html匹配B。首先查找匹配的前缀字符,找到最长匹配是配置B,接着按照顺序查找匹配的正则表达式。结果没有找到,因此使用之前标记的最长匹配,即配置B。
请求/documents/index.html匹配C。首先找到最长匹配C,由于后面没有匹配的正则表达式,所以使用之前标记的最长匹配C。
请求/documents/1.jpg匹配E。首先进行前缀字符查找,找到最长匹配C。然后按照正则匹配查找,找到匹配E,因此使用E。
请求/images/1.jpg匹配D。首先进行前缀字符查找,找到最长匹配D。由于location D使用了^~,按照上图的规则,匹配到后就不再往下找,所以使用了匹配D。加入这里没有^~,那么最终会匹配到E。
rewrite指令
将regex指定的url替换成replacement这个新的url(可以使用正则表达式及变量提取)。
当replacement以http://或https://或者$schema开头,则直接返回302重定向。
替换后的url根据flag指定的方式进行处理
last:用replacement这个URL进行新的location匹配
break:break指令停止当前脚本指令的执行,等价于独立的break指令
redirect:返回302重定向
permanent:返回301重定向
Syntax: | rewrite regex replacement [flag]; |
---|---|
Default: | — |
Context: | server , location , if |
例如如下nginx.conf配置,访问以下地址:
这里1.txt的内容为1,2.txt内容为2,3.txt内容为3
[root@VM_16_4_centos conf]# curl localhost:8080/first/3.txt 3 [root@VM_16_4_centos conf]# curl localhost:8080/second/3.txt 3 [root@VM_16_4_centos conf]# curl localhost:8080/third/3.txt third!
可见,访问/first/3.txt和second/3.txt是被做了重定向的。
同样的,访问/redirect1、/redirect2、/redirect3、/redirect4返回如下:
[root@VM_16_4_centos redirect4]# curl localhost:8080/redirect1 -I HTTP/1.1 301 Moved Permanently Server: nginx Date: Thu, 18 Jul 2019 01:09:57 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Location: [root@VM_16_4_centos redirect4]# curl localhost:8080/redirect2 -I HTTP/1.1 302 Moved Temporarily Server: nginx Date: Thu, 18 Jul 2019 01:10:01 GMT Content-Type: text/html Content-Length: 154 Connection: keep-alive Location: [root@VM_16_4_centos redirect4]# curl localhost:8080/redirect3 -I HTTP/1.1 302 Moved Temporarily Server: nginx Date: Thu, 18 Jul 2019 01:10:03 GMT Content-Type: text/html Content-Length: 154 Connection: keep-alive Location: http://localhost [root@VM_16_4_centos redirect4]# curl localhost:8080/redirect4 -I HTTP/1.1 301 Moved Permanently Server: nginx Date: Thu, 18 Jul 2019 01:10:07 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Location: http://localhost
server { server_name localhost; listen 8080; rewrite_log on; error_log logs/rewrite_error.log notice; root html/; location /first { rewrite /first(.*) /second$1 last; return 200 'first!\n'; } location /second { rewrite /second(.*) /third$1 break; #rewrite /second(.*) /third$1; return 200 'second!\n'; } location /third { return 200 'third!\n'; } location /redirect1 { rewrite /redirect1(.*) $1 permanent; } location /redirect2 { rewrite /redirect2(.*) $1 redirect; } location /redirect3 { rewrite /redirect3(.*) http://localhost$1; } location /redirect4 { rewrite /redirect4(.*) http://localhost$1 permanent; } }
例如下面我们要重新写一个url
location /blog { # 文章详情页 # http://localhost/blog/article.php?id=12 -> http://localhost/blog/article-12.html rewrite article-(\d+)-.*\.html /blog/article.php?id=$1; }
更多nginx的配置可以参考学习h5bp开源项目。
常用正则匹配
元字符
.
: 匹配除换行符以外的任意字符\w
: 匹配字幕或数字或下划线或汉字\s
:匹配任意的空白符\d
:匹配数字\b
:匹配单词的开始或结束^
: 匹配字符串的开始$
: 匹配字符串的介绍 重复?
: 重复0次或1次+
: 重复1次或更多次*
: 重复0次或更多次{n}
: 重复n次{n,}
: 重复n次或更多次[c]
: 匹配单个字符c[a-z]
: 匹配a-z小写字母的任意一个
转载请备注来源: 《Nginx配置文件(nginx.conf)详解》 | shuwoom.com
加入这里没有^~,那么最终会匹配到E。加入写错了,应该是假如吧