Nginx-将子域作为变量

时间:2018-12-05 16:26:37

标签: nginx subdomain config

我有几个具有相同行为的子域(基于子域名),我试图为nginx服务器找到开销较小的最佳解决方案。 在该域上,还有默认的www和非www域,还有通配符(那些“成对的”子域不应与通配符匹配)。

到目前为止,我已经找到3种可能的解决方案:

  1. 在单独的服务器块中定义每个子域,并对子域进行硬编码

    server {
        server_name one.domain;
        # config with "one"
    }
    server {
        server_name two.domain;
        # same config with "two"
    }
    ... three, four etc.
    

这应该没问题,但是不是DRY(不要重复自己) 而且很长,看起来很丑

  1. 在正则表达式中捕获server_name

    server {
        server_name  ~^(?<subdomain>one|two|three|...)\.domain\.com$;
        # config with $subdomain
    }
    

config更干净,但是有一个正则表达式开销,也可能与通配符虚拟主机交互,我不确定哪个优先级

  1. 静态主机名加地图

    server {
        server_name one.domain two.domain three.domain ....;
        # config with $subdomain, where $subdomain is a map based on $server_name, extracting all characters before .
    }
    

这应该是最好的方法,虚拟主机的选择基于字符串比较(没有regexp),但是在该“映射”中我仍然有regexp用法

问题是:第三种解决方案可以改进吗?

就像在不使用正则表达式的情况下提取字符串的一部分(即从$ server_name中的$ subdomain)一样?

所有子域都处于同一级别,并且都以.domain结尾

0 个答案:

没有答案