snippets/ 是运维为提升可维护性主动创建的公共配置复用层,专存合法指令块(如location、if、add_header),必须被include到正确上下文才生效,严禁含upstream等全局指令。

snippets/ 文件夹不是 Nginx 默认自带的,而是运维实践中为提升可维护性主动创建的公共配置复用层。它不承担业务路由逻辑,只封装高频、跨站点、语义明确的通用指令块,让 server 和 location 块保持干净。
snippets 目录的核心定位
-
存放「可插入片段」:内容必须是合法的 Nginx 指令块(如
location {}、if {}、add_header等),不能包含upstream、server或顶层指令。 -
不独立生效:必须被
include到正确上下文(如server块内、location块内),否则语法报错。 -
路径推荐用绝对路径或从
/etc/nginx/起始的相对路径,避免因当前文件位置不同导致加载失败。
常见可提取到 snippets 的公共配置类型
-
安全头统一设置
snippets/security-headers.confadd_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "DENY" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer-when-downgrade" always;
-
CORS 预检响应
snippets/cors-preflight.conflocation = / { if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin "*" always; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always; add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization" always; add_header Access-Control-Max-Age "86400" always; add_header Access-Control-Allow-Credentials "true" always; add_header Access-Control-Expose-Headers "X-Total-Count" always; add_header Content-Length 0; add_header Content-Type text/plain; return 204; } } -
反向代理基础参数
snippets/proxy-params.confproxy_set_header Host $http_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_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
-
认证头透传规则
snippets/auth-header-proxy.confproxy_set_header Authorization $http_authorization; proxy_pass_request_headers on;
正确引入方式示例
在某个业务配置文件(如 /etc/nginx/conf.d/user-api.conf)中:
server {
listen 443 ssl;
server_name api.example.com;
include snippets/ssl-params.conf; # SSL 公共参数(证书、协议等)
include snippets/security-headers.conf; # 安全响应头
include snippets/proxy-params.conf; # 代理基础头
location /v1/ {
proxy_pass http://user-backend;
include snippets/auth-header-proxy.conf; # 透传 Auth 头
}
}
注意事项
-
snippets/中的文件不能包含upstream、map或http块,它们属于全局作用域,应放在upstreams/或nginx.conf的http{}顶层。 - 同一
snippets/文件不要混用多个职责(比如把 SSL 参数和安全头写进同一个文件),职责越单一,复用越灵活。 - 修改后务必执行
nginx -t验证语法,再nginx -s reload生效。
不复杂但容易忽略路径和上下文匹配,只要结构清晰、职责分明,snippets 就能真正成为配置减负的关键层。











