Nginx用include通配符批量加载子域名配置,关键是将每个子域名的server{}块独立成.conf文件(如api.example.com.conf),通过绝对路径+*.conf在http块中统一引入,按ASCII序加载,推荐sites-available/sites-enabled软链模式管理,并每次用nginx -t验证语法后reload。

在 Nginx 中用 include 通配符导入多套子域名配置,关键是把每个子域名的 server{} 块单独写成一个文件,再通过带 * 的绝对路径统一加载——不是靠自动识别子域,而是靠人工组织文件结构实现批量管理。
目录结构要清晰,按子域名分文件
把每个子域名(如 api.example.com、blog.example.com、shop.example.com)各自写成独立的 .conf 文件,放在统一目录下,例如:
/etc/nginx/sites-enabled/api.example.com.conf/etc/nginx/sites-enabled/blog.example.com.conf/etc/nginx/sites-enabled/shop.example.com.conf
每个文件只包含一个完整的 server{} 块,开头用 server_name 明确声明对应子域名,比如:
server {
listen 80;
server_name api.example.com;
location / { proxy_pass http://backend-api; }
}主配置里用绝对路径 + 通配符加载
在 /etc/nginx/nginx.conf 的 http{} 块末尾,写一行带根路径的 include:
http {
# ... 其他全局设置(mime、log_format、upstream 等)
include /etc/nginx/sites-enabled/*.conf;
}必须用绝对路径,不能写 include sites-enabled/*.conf —— 否则 Nginx 会以 nginx.conf 所在目录为基准拼接,容易出错。通配符按文件名 ASCII 顺序加载,建议加数字前缀控制依赖关系,例如:
01-api.example.com.conf02-blog.example.com.conf99-shop.example.com.conf
启用/禁用子域名靠软链接更安全
推荐用 sites-available + sites-enabled 模式管理:
- 所有子域名配置先放
/etc/nginx/sites-available/ - 启用时执行:
ln -sf ../sites-available/api.example.com.conf /etc/nginx/sites-enabled/api.example.com.conf - 停用时直接删软链,不删源文件,避免误操作
这样 reload 时只加载 sites-enabled/ 下的真实链接,空文件、备份文件(如 .conf.bak)或隐藏文件(如 .swp)不会被误读。
每次改完都要验证语法再重载
新增或修改子域名配置后,务必执行:
nginx -t
它能精准报出哪个子配置文件哪一行有错。验证通过再执行:
nginx -s reload
注意:Nginx 不支持在子配置文件中再嵌套 include,所有层级必须扁平化;也不支持变量或动态路径,* 只匹配文件系统已存在的 .conf 文件。


















