如何使用正则表达式在 nginx 中将变量分解为单独的变量

how to break a variable into seperate variables in nginx using regex

我有一个开发服务器设置,它执行一些动态生根,允许我通过检测 server_name 中的域和子域并使用它来设置根来设置快速测试项目。

server_name ~^(?<subdomain>\w*?)?\.?(?<domain>\w+\.\w+)$;

效果很好,允许我根据变量 $subdomain 和 $domain

设置根路径

虽然对于特定类型的项目,我还需要能够根据子域是否包含破折号将子域变量进一步拆分为两个变量。

例如

mysubdomain 不应拆分,而应保留为变量 $subdomain,

但是 mysubdomain-tn 将被分成 2 个变量 $subdomain$version

您需要将正则表达式复杂化一点:

server_name ~^(?<subdomain>\w*?)(-(?<version>\w*?)?)?\.?(?<domain>\w+\.\w+)$;

编辑:

有几种方法可以调试 Nginx 配置,包括 debugging log, echo module and, in some extreme situations, even using a real debugger. However, in most cases adding custom headers 响应足以获取必要的信息。

例如,我使用这个简单的配置测试了上面的正则表达式:

server {
    listen 80;

    server_name ~^(?<subdomain>\w*?)(-(?<version>\w*?)?)?\.?(?<domain>\w+\.\w+)$;

    # Without this line your browser will try to download
    # the response as if it were a file
    add_header Content-Type text/plain;

    # You can name your headers however you like
    add_header X-subdomain "$subdomain";
    add_header X-domain "$domain";
    add_header X-version "$version";

    return 200;
}

然后我将域 mydomain.local、mysubdomain-tn.mydomain.local 和 mysubdomain-tn.mydomain.local 添加到我的 hosts file, opened them in a browser with open debug panel (F12 in most browsers) and got the results.