nginx 配置中的 set variable 问题

2015-03-25 16:47:48 +08:00
 maikcn

[前情提要]
因为要维护一批(大约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;
}
6649 次点击
所在节点    问与答
2 条回复
maikcn
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
2015-03-25 17:43:39 +08:00
可以尝试geo转义$符号,
http://blog.sina.cn/dpool/blog/s/blog_6d579ff40100wi7p.html

推荐看一下ngx_lua, CDN厂商的解决方案

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/179292

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX