[英]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配置的方法,包括調試日志 , 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;
}
然后,將域mydomain.local,mysubdomain-tn.mydomain.local和mysubdomain-tn.mydomain.local添加到我的主機文件中,在帶有打開調試面板的瀏覽器中打開它們(在大多數瀏覽器中為F12),並得到結果 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.