[英]Redirecting a subdomain with a regular expression in nginx
Nginx文檔說server_name指令支持正則表達式。 我一直把頭撞在牆上,試圖使瑣碎的正則表達式正常工作。
我想將http://subdomain.mydomain.com重定向到http://mydomain.com/subdomain
這是我的代碼。
server {
server_name "~^subdomain\.mydomain\.com$";
rewrite ^ http://mydomain.com/subdomain;
}
另外,可能值得注意。 在nginx配置文件中,還有一個規則:
server {
server_name *.mydomain.com
...
}
我究竟做錯了什么?
更新:
有人建議我不要為此使用正則表達式...以便提供更多的清晰度:瑣碎的正則表達式僅用於故障排除。 真正的正則表達式看起來更像是...
server {
server_name "~^.*(cvg|cincinnati)\.fakeairport(app)?\.(org|com)$";
rewrite ^ http://fakeairport.com/cincinnati;
}
server {
server_name "~^.*(lex|lexington)\.fakeairport(app)?\.(org|com)$";
rewrite ^ http://fakeairport.com/lexington;
}
因此,最好使用正則表達式。
回答舊問題以幫助他人
使用nginx 1.1.19,您可以執行以下操作:
server {
server_name ~^(?<subdomain>\w+)\.domainA\.com$;
location / {
rewrite ^ https://$subdomain.domainB.com$request_uri permanent;
}
}
匹配domainA.com之前的子域並將其存儲在變量$ subdomain中,然后可以在重寫中使用它。 這僅用一個服務器指令將xxx.domainA.com之類的URL重寫為xxx.domainB.com。
與NGINX一起愛正則表達式!
由於我經常使用多個域名,並且我希望保持配置盡可能整潔和堅如磐石,因此我幾乎總是將regex與nginx結合使用。
在這種情況下,我已經使用以下正則表達式解決了它:
server {
listen 80;
server_name ~^((?<subdomain>.*)\.)(?<domain>[^.]+)\.(?<tld>[^.]+)$;
return 301 $scheme://${domain}.${tld};
}
它的作用如下:指向該服務器(IP地址)的每個subdomain.domain-name.tld
都會自動重定向到domain-name.tld
。
因此,例如www.myexampledomain.com
重定向到myexampledomain.com
。
要回答這個問題,您還可以執行以下操作:
server {
listen 80;
server_name ~^((?<subdomain>.*)\.)(?<domain>[^.]+)\.(?<tld>[^.]+)$;
return 301 $scheme://${domain}.${tld}/${subdomain};
}
現在, mysubdomain.myexampledomain.com
轉換為myexampledomain.com/mysubdomain
。
regex很棒,因為您可以隨意扔任何東西,它將為您轉換。
如果您閱讀server_name匹配規則 ,則會看到在正則表達式名稱之前但在確切的主機名之后檢查了前綴和后綴server_names。 由於* .mydomain.com匹配,因此未測試正則表達式。 它在配置中較早列出的事實沒有區別。 由於您只是想將單個主機名與您的正則表達式匹配,因此很簡單:
server {
server_name subdomain.mydomain.com;
rewrite ^ http://mydomain.com/subdomain$request_uri?;
}
server {
server_name *.mydomain.com;
# stuff
}
將為您工作。
只是作為評論。 如果要將所有子域級別重定向到第一個子域級別,例如在使用通配符SSL證書時將util重定向,則可以使用:
server {
listen 80;
server_name ~^(.*)\.(?<subdomain>\w+).mydomain\.com$;
return 301 https://$subdomain.mydomain.com$request_uri;
}
server {
listen 80;
server_name ~^(?<subdomain>\w+).mydomain\.com$;
return 301 https://$subdomain.mydomain.com$request_uri;
}
第一個是將HTTP多級子域重定向到https中的第一個子域級別。 接下來是將http中的第一級子域重定向到https中的相同子域。
我知道每個人都在說nginx配置文件中是否有害,但有時您無法以其他任何方式解決。
server {
server_name .mydomain.com;
if ( $host ~ subdomain.mydomain.com ) {
rewrite ^(.*) http://mydomain.com/subdomain$1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.