在声明`server_name`时,如何在正则表达式模式中使用nginx变量

时间:2017-09-30 13:10:03

标签: nginx

在我的系统上进行开发时,我使用server_name ~^(?<subdomain>.+)\.localhost$;来捕获子域,但是,在生产中,我的反向代理部署在多个域上,域名存储在nginx变量$domain中。

如何在进行字符串插值的同时进行正则表达式捕获。

E.g。而不是server_name ~^(?<subdomain>.+)\.localhost$我如何做server_name ~^(?<subdomain>.+)\.${domain}$;

实际代码:

  server {
    listen       80;
    server_name ~^(?<subdomain>.+)\.localhost$;

    location / {
        proxy_pass https://sarahah.com; # get the joke? ;)
        proxy_set_header Host $subdomain.sarahah.com;
    }

1 个答案:

答案 0 :(得分:3)

跳过并尝试阅读文档后,我放弃并创建了一个nginx.conf.erb文件,我用Ruby nginx.conf编译成ERB

说真的,如果你是来自未来并且想要解决这个问题,那么请使用ERB文件。这比编写几十个bash echo更好,可以将你的环境变量放到nginx.conf中,这是我整周做的最好的事情。

我的代码现在看起来像:

server {
    listen       80;
    server_name ~^(?<subdomain>.+)\.<%= ENV['DOMAIN'] %>$;

    location / {
        proxy_pass https://sarahah.com; # get the joke? ;)
        proxy_set_header Host $subdomain.sarahah.com;
    }