nginx 配置文件结构

2021-12-07  本文已影响0人  偷油考拉

一、配置文件结构

nginx由配置文件中配置的指令所控制的模块组成。
指令被区分为:简单指令simple directives,块指令 block directives

简单指令 simple directive

简单指令由名称 (name) 和参数 (parameters) 组成,以空格分隔,以分号结尾。

块指令 block directive

块指令与简单指令结构类似,但不是分号结尾,而是由大括号({})包围的一组附加指令。
如果块指令在大括号内包含了其他指令,则称其为上下文 context,例如:

配置文件中,不在任何上下文内的指令,被视为位于主上下文 main context 中。事件和http指令位于主上下文、http中的服务器和服务器中的位置。
events and http 指令在main context 内,serverhttp内,locationserver 内。

# 后的内容代表注释。

二、创建配置文件

NGINX 配置文件的基本元素,包含:指令directives 、 上下文contexts

NGINX 和其他服务一样,配置文件都是特定格式的文本文件。默认,文件名是 nginx.conf,位于 /etc/nginx 目录。(也有可能是/usr/local/nginx/conf, or /usr/local/etc/nginx,取决于各自安装环境。)

指令 Directives

配置文件由指令和它们的参数组成。
简单指令Simple (single‑line) directives 由分号结尾;
其他指令,像 容器containers 一样,把相关的指令聚合到一起,以大括号 ( {} )包含起来;通常引用为blocks.

如下是简单指令的一些范例:

user             nobody;
error_log        logs/error.log notice;
worker_processes 1;
特定配置 Feature-Specific Configuration Files

为了简化配置的管理,建议将特定功能分开,一些feature‑specific files存放到/etc/nginx/conf.d目录,在主文件nginx.conf中使用include指令引用。

include conf.d/http;
include conf.d/stream;
include conf.d/exchange-enhanced;
上下文 Contexts

一些 top‑level 指令,作为 contexts,将应用于不同流量类型的一些指令组合在一起:

在这些 contexts 的 Directives 被认为在 main context 内。

虚拟主机 Virtual Servers

在每个处理流量的上下文中,你可以包含一个or多个 server 块来定义 virtual serversvirtual servers 配置请求的处理。server 上下文内可以包含的指令,取决于流量类型。

多上下文配置范例 Sample Configuration File with Multiple Contexts

如下配置文件展示了上下文的架构。

user nobody; # a directive in the 'main' context

events {
    # configuration of connection processing
}

http {
    # Configuration specific to HTTP and affecting all virtual servers  

    server {
        # configuration of HTTP virtual server 1       
        location /one {
            # configuration for processing URIs starting with '/one'
        }
        location /two {
            # configuration for processing URIs starting with '/two'
        }
    } 
    
    server {
        # configuration of HTTP virtual server 2
    }
}

stream {
    # Configuration specific to TCP/UDP and affecting all virtual servers
    server {
        # configuration of TCP virtual server 1 
    }
}

继承 Inheritance

通常,child 上下文 – 包含在另外一个上下文 (its parent) 中的上下文 – 继承父层的指令设置。一些指令可以出现在多个上下文中,这种情况下,child context 的指令可以覆写继承自 parent context 的指令设置。比如:proxy_set_header 指令。

上一篇下一篇

猜你喜欢

热点阅读