Nginx 通过 include 将跨域、鉴权等通用逻辑抽离为职责单一的 snippets 片段,仅限在 location 或 server 块内引用,要求语法合法、作用域匹配、命名明确、路径规范,并需 nginx -t 验证。

Nginx 使用 include 将各路由节点独立为 snippets 片段,本质是把原本混在 location 块里的通用逻辑(如跨域、鉴权透传、请求改写、错误响应等)抽离成职责单一、可复用的配置文件,并通过 include 精准注入到对应上下文。关键不在“能 include”,而在“在哪 include、include 什么、怎么命名、如何保证合法”。
snippets 目录专用于存放可插拔的 location 级片段
它不放 upstream、不放 server,只放能在 location 或 server 内直接使用的指令块,比如:
-
cors-preflight.conf:专门处理浏览器预检请求 -
auth-proxy.conf:统一设置proxy_set_header Authorization $http_authorization;等 -
json-body-limit.conf:限制application/json请求体大小 -
rewrite-api-v1.conf:对/api/v1/下所有路径做前缀重写
这些文件内容必须语法合法、作用域匹配。例如:
# /etc/nginx/snippets/cors-preflight.conf
location = / {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin "$http_origin" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type, X-Requested-With, Authorization" always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Max-Age "86400" always;
add_header Access-Control-Expose-Headers "X-Total-Count" always;
return 204;
}
}
这个文件只能被 include 在 server 块内,不能放在 http 顶层,也不能嵌套在另一个 location 里——否则 Nginx 启动会报错。
在 server 块中按需 include,不堆砌、不冗余
每个 location 只加载它真正需要的 snippet,避免“一刀切”式引入:
server {
listen 443 ssl;
server_name api.example.com;
# 公共头、超时等基础设置(来自 conf.d/common.conf)
include conf.d/common.conf;
# 路由节点 1:用户接口
location /api/v1/users {
include snippets/auth-proxy.conf;
include snippets/cors-preflight.conf;
proxy_pass http://upstream-users;
}
# 路由节点 2:订单接口,需额外限流
location /api/v1/orders {
include snippets/auth-proxy.conf;
include snippets/rate-limit.conf; # 单独定义的限流片段
proxy_pass http://upstream-orders;
}
# 路由节点 3:静态资源,跳过鉴权
location /static/ {
alias /var/www/static/;
expires 1h;
add_header Cache-Control "public, immutable";
}
}
注意:include snippets/xxx.conf 必须出现在 location 块内部(或 server 块顶层),且所 include 的文件内容必须是 Nginx 允许在此层级出现的指令(如 add_header、proxy_set_header、if、return 等),不能含 upstream、map、log_format 等全局指令。
命名与路径要稳定、可预期
- 统一用绝对路径或从
/etc/nginx/出发的相对路径:include snippets/cors-preflight.conf;✅,include ./snippets/cors.conf;❌(.指向主配置目录,易错) - 文件名体现用途和粒度:
auth-header-proxy.conf比headers.conf更明确;rate-limit-per-ip.conf比limit.conf更不易冲突 - 不在 snippets 里写
location嵌套逻辑,每个 snippet 应是一个原子能力单元(一个功能,一个文件)
验证与维护要点
- 修改任一片段后,必须运行
nginx -t—— 错误会精确报到该 snippet 的某一行 - 多个 snippet 可能设置相同 header(如都加
X-Request-ID),需协调顺序或统一入口,避免覆盖 - 避免在不同 snippet 中重复定义变量(如
$backend_url),这类应提至map或set块,放在http级
这样拆分后,新增一个 /api/v1/reports 路由,只需复制粘贴一段 location,再 include 几个已有 snippet,不用重写鉴权头、跨域逻辑或超时参数。运维灰度某个路由时,也能单独注释或替换其 include 行,不影响其他节点。











