大网数据广告活动
服务器运维问答

Dynamic include Nginx config snippets for vhosts

· 52CE 我爱测

I try to configure vhosts with and without additional per-vhost config with nginx. I think of something like this: server { listen 81; server_name ~^(www\.)?(?<sname>.+?)$; root /var/www/$sname; include /etc/nginx/sites/$sname; a…

问题原文

原帖链接 · allo · CC BY-SA 3.0

I try to configure vhosts with and without additional per-vhost config with nginx. I think of something like this:

server {
    listen 81; 
    server_name ~^(www\.)?(?<sname>.+?)$;
    root /var/www/$sname;
    include /etc/nginx/sites/$sname;
    access_log /var/log/nginx/$sname/access.log;
    error_log /var/log/nginx/$sname/error.log;
}

Then i could just touch /etc/nginx/mysite.example.com to add a new site with static html, while i can edit the file for the vhost to add for example a reverse proxy directive or some rewrite rules.

The problem is, nginx seems to include the config when starting. And it would be more clean to have something like

for $config in /etc/nginx/sites:
    {
        server_name $config
        root /var/www/$config
        include $config
        [...]
    }

which should run at the start and not on the first request to the vhost.

已采纳解答

原帖链接 · allo · CC BY-SA 4.0

I still do not know, if a script include is possible, but i am using a script to generate the static config now using jinja2 as template system.

An alternative to using an own script is to use the ansible template module. When using ansible it can also be much faster to create one large configuration instead of many snippets, which won't hurt as the templates used by ansible can still be small snippets that are concatenated when creating the autogenerated config.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-07-05)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。