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

Fin*_*ish 1 regex nginx

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

server_name ~^(?<subdomain>\w*?)?\.?(?<domain>\w+\.\w+)$;
Run Code Online (Sandbox Code Playgroud)

这很好用,允许我根据变量$ subdomain和$ domain设置根路径

但是对于特定类型的项目,如果子域包含破折号,我还需要能够进一步将子域变量拆分为两个变量.

例如

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

mysubdomain-tn将分为2个变量$ subdomain$ version

Iva*_*lev 5

您需要使正则表达式更复杂一点:

server_name ~^(?<subdomain>\w*?)(-(?<version>\w*?)?)?\.?(?<domain>\w+\.\w+)$;
Run Code Online (Sandbox Code Playgroud)

编辑:

有几种方法可以调试Nginx配置,包括调试日志,echo模块,在某些极端情况下,甚至使用真正的调试器.但是,在大多数情况下,向响应添加自定义标头足以获取必要的信息.

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

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我将域mydomain.local,mysubdomain-tn.mydomain.local和mysubdomain-tn.mydomain.local添加到我的hosts文件中,在打开的调试面板(大多数浏览器中为F12)的浏览器中打开它们并获得结果.