V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
maikcn
V2EX  ›  问与答

nginx 配置中的 set variable 问题

  •  
  •   maikcn · 2015-03-25 16:47:48 +08:00 · 6639 次点击
    这是一个创建于 3313 天前的主题,其中的信息可能已经有所发展或是发生改变。

    [前情提要]
    因为要维护一批(大约20个)网站的 nginx 配置,配置的主要内容基本上是将域名的访问反向代理到本地各个端口的服务中,每段 server 的配置不同的地方只有域名和端口两项而已,所以想偷懒看是否能将重复的内容通过 include 外部的 conf 文件复用起来,外部只传入不同的参数来达到产生不同的配置,于是我写了下面2个配置文件

    但是结果是不行的,现在不是很清楚到底是 variables 的命名不能重复,或者是 include 的内容不能传入 variables,还是这样的写法本来就是不对的

    所以看看各位能否指点一下,如何实现这样的偷懒写法?谢谢了!

    nginx.conf 文件中

    server {
        set $cus_domain_name "www.example1.com";
        set $cus_port 50001;
        include nginx_include.conf;
    }
    
    server {
        set $cus_domain_name "www.example2.com";
        set $cus_port 50002;
        include nginx_include.conf;
    }
    

    nginx_include.conf 文件中

    listen 443 ssl;
    server_name $cus_domain_name;
    
    ssl_certificate test.crt;
    ssl_certificate_key test.key;
    access_log /var/log/nginx/$cus_domain_name.access.log;
    error_log /var/log/nginx/$cus_domain_name.error.log;
    
    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://127.0.0.1:$cus_port;
    }
    
    2 条回复    2015-03-25 17:43:39 +08:00
    maikcn
        1
    maikcn  
    OP
       2015-03-25 17:10:30 +08:00
    又翻了一遍,找到下面2个文章,貌似是无解?
    http://forum.nginx.org/read.php?2,143479
    http://nginx.2469901.n2.nabble.com/variables-in-quot-include-quot-for-vhost-specific-config-files-td3285213.html

    这里理解有点难度,是指变量是在运行时才会被产生并解释,但是如果跨越了一层 include 的话就被视为是静态内容了?
    nginx "include"s files on start time, while "root", etc. substitute variable values on run time.
    LazyZhu
        2
    LazyZhu  
       2015-03-25 17:43:39 +08:00 via iPhone   ❤️ 1
    可以尝试geo转义$符号,
    http://blog.sina.cn/dpool/blog/s/blog_6d579ff40100wi7p.html

    推荐看一下ngx_lua, CDN厂商的解决方案
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2828 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 11:34 · PVG 19:34 · LAX 04:34 · JFK 07:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.