nginx的include指令用于模块化配置管理,支持在http、server、location等上下文中按路径或通配符引入配置文件,实现功能分离与复用,但不支持变量展开且需注意权限与循环引用。

Nginx 的 include 指令是模块化管理配置的核心手段,它让主配置文件(如 nginx.conf)保持简洁,同时支持按功能、环境或站点拆分配置片段,便于协作、复用和维护。
include 的基本语法与作用范围
include 不是独立指令,必须出现在上下文(context)中,且仅在该上下文中生效。常见可用位置包括:http、server、location、upstream 等块内。
- 语法格式为:
include /path/to/file.conf;或支持通配符:include /etc/nginx/conf.d/*.conf; - 路径可以是绝对路径,也可以是相对路径(相对于 Nginx 启动时的
--prefix目录,默认通常是/usr/local/nginx) - 被 include 的文件内容会原样插入到当前上下文中,相当于“复制粘贴”,因此不能跨上下文使用指令(例如在
server块里 include 一个含http指令的文件会报错)
典型实战目录结构设计
推荐将配置按职责分层组织,例如:
/etc/nginx/
├── nginx.conf # 主配置:定义 events/http 全局参数,只 include http 块
├── conf.d/
│ ├── common.conf # 公共基础配置(日志格式、超时、安全头等)
│ ├── ssl.conf # SSL 通用参数(证书路径、协议、密钥交换等)
│ └── sites-enabled/
│ ├── example.com.conf
│ └── api.internal.conf
└── snippets/
├── proxy-params.conf # 反向代理常用 header 设置
└── deny-bots.conf # 屏蔽恶意爬虫的 map + if 规则
这样划分后,每个站点配置只需关注自身逻辑,重复项统一维护在 snippets/ 或 conf.d/ 中。
常用 include 场景与写法示例
✅ 站点配置分离:
在 nginx.conf 的 http 块末尾加入:
include /etc/nginx/conf.d/sites-enabled/*.conf;
然后每个 *.conf 文件就是一个完整 server 块,比如 example.com.conf:
server {
listen 80;
server_name example.com;
include snippets/redirect-to-https.conf;
}
<p>server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include snippets/ssl.conf;
include snippets/proxy-params.conf;
location / {
proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;
}
}</p>✅ 复用反代参数:snippets/proxy-params.conf 内容示例:
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_buffering off;
✅ 条件性加载(配合变量需谨慎):include 本身不支持变量展开(如 include /etc/nginx/conf.d/$env.conf; 会报错),但可通过符号链接实现环境切换:
- 准备
staging.conf和production.conf - 创建软链:
ln -sf staging.conf /etc/nginx/conf.d/current.conf - 主配置中写:
include /etc/nginx/conf.d/current.conf;
调试与排错要点
include 错误常导致 Nginx 启动失败,但错误提示可能不够直观。关键检查点:
- 执行
nginx -t永远是第一步,它会递归验证所有被 include 的文件语法 - 注意文件权限:Nginx 主进程以 root 运行,但 worker 进程通常以
www-data或nginx用户读取配置,确保该用户对 include 路径有读取权限 - 避免循环 include:A.conf include B.conf,B.conf 又 include A.conf —— 会导致解析器崩溃
- 通配符匹配为空时,Nginx 不报错也不警告(静默跳过),可临时加个空文件或用
ls /path/*.conf确认是否真有匹配项











