2.1.2 配置文件
设置或修改NGINX及其模块的工作方式,是通过修改NGINX配置文件完成的,熟悉了NGINX配置,也就大体明白了NGINX是如何工作的。我们在网关的建设中,会经常修改 NGINX 配置文件。
默认的配置文件会在安装时会自动创建,通常位于 /etc/nginx 目录。开发者也可以创建自己的配置文件,并通过 nginx -c filename 在启动的时候指定。
1.配置文件的结构
一个典型的配置文件,其结构如下所示。
user root;
worker_processes auto;
events {
worker_connections 1024;
}
http {
sendfile on;
gzip on;
access_log /var/log/nginx/access.log
error_log /var/log/nginx/error.log
server {
listen 80;
server_name www.example.com;
location / {
root /var/www/www.example.com;
}
}
}上述的 events,http,server,location 属于块指令,每个块指令使用一组大括号包裹,里面还会有若干条配置项(也成为“简单指令”)或子级块指令。这些块指令,就被称为其内部指令的“上下文(context)”。
上下文(context):
之所以划分出多个块指令,是因为不同的配置项作用的级别是不一样的。events 块作用于TCP连接级别,其中的worker_connections 配置项规定了单个 worker 进程可以同时打开的最大TCP连接数。http 作用于 HTTP 服务级别,其中的 gzip 指令指示是否对 HTTP 响应开启 gzip 压缩。server 作用于特定的 HTTP 虚拟服务器,而 location 块中的指令,只能作用于特定的 URL。
虚拟服务器:
上面的NGINX配置文件实例,其作用逐行说明如下。
user
user user [group];
指定 worker 进程使用的操作系统用户名和群组
worker_processes
worker_processes number | auto;
指定 worker 进程数量,当值为 auto 时,则为当前服务器的CPU内核数量
events
-
块指令
+ worker_connections
worker_connections number;
指定单个 worker 进程可以同时打开的最大TCP连接数
http
-
块指令
+ sendfile
sendfile on | off;
受否启用 sendfile(),该配置项控制NGINX如何将文件读取到内存中,设置为 on 可以加快NGINX对文件的处理速度。
+ gzip
gzip on | off;
是否对HTTP响应开启 gzip 压缩
+ access_log
access_log path | off;
设置访问日志信息,还可以通过额外的参数设置日志的格式等
+ error_log
error_log file [level];
设置错误日志信息
+ server
-
块指令
++ listen
listen address | port | unix
设置HTTP服务监听端口号等
++ server_name
server_name name ...;
虚拟服务器的名称
++ location
-
块指令
+++ root
root path;
设置HTTP请求对应的根目录
Last updated