Nginx

重寫uri以刪除nginx中的www

  • March 1, 2021

我有未知數量的域與www.abc123.example.com. “abc”後面的數字是未知的。我想也許我可以使用正則表達式的重寫規則~*(www\.abc\w+)

就像是:

server_name ~*(www\.abc\w+)
rewrite ~*(www\.abc\w+)\.example\.com (abc\w+)\.example\.com;

不幸的是,這似乎不起作用,並且 uri 沒有改變。我的其他想法可能是嘗試設置/重寫 $uri 值,但我也沒有成功。

我不確定我是否未能匹配 uri 值或未能重寫 uri(或兩者兼而有之)。

我能夠做到這一點:

if ($host ~* ^www\.(.*)) {       
set $host_without_www $1;
rewrite ^(.*) http://$host_without_www$1 permanent;
}

不幸的是,這會重寫所有“www”流量,而不僅僅是 www.abc123。任何幫助表示讚賞。謝謝你。

嘗試以下方法:

server {
   server_name ~ ^www\.(?<newdomain>abc[0-9]+\.example\.com)$;

   return 301 https://$newdomain$request_uri;
}

這將匹配 domain www.abcN.example.com,其中N是一位或多位數字。正則表達式會將部分擷取abcN.example.com到變數$newdomain中。

然後在返回語句中,我們使用之前擷取的變數和請求的 URI 部分建構目標 URL。

引用自:https://serverfault.com/questions/1055537