本文介绍了声明`server_name`时如何在正则表达式模式中使用nginx变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When developing on my system, I use server_name ~^(?<subdomain>.+)\.localhost$; to capture the subdomain, however, in production, my reverse proxy is deployed over multiple domains and the domain name is stored in the nginx variable $domain.

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

How do I do a regex capture while doing string interpolation at the same time.

例如而不是server_name ~^(?<subdomain>.+)\.localhost$我该怎么做server_name ~^(?<subdomain>.+)\.${domain}$;

E.g. instead of server_name ~^(?<subdomain>.+)\.localhost$ how do I do 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;
    }

推荐答案

在跳转并尝试阅读文档后,我有点放弃并创建了一个nginx.conf.erb文件,并使用Ruby的ERB将其编译为nginx.conf

After jumping around and trying to read documents, I kinda gave up and created an nginx.conf.erb file, that I compile into nginx.conf with Ruby's ERB.

严重的是,如果您来自未来,并且想尽办法解决此问题,请使用ERB文件.比编写数十个bash echo脚本更好地将环境变量放入nginx.conf更好,这是我整周所做的最好的事情.

Seriously, if you're from the future and banging your head to fix this, just go with the ERB file. It's better than scripting dozens of bash echos to get your environment variables into the nginx.conf and it's the best thing I did all week.

我的代码现在看起来像:

My code now looks like:

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

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

这篇关于声明`server_name`时如何在正则表达式模式中使用nginx变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 06:13