Rewrite uri to remove www in nginx
I have an unknown number of domains that match a pattern like www.abc123.example.com
. Where the number after "abc" is unknown. I thought perhaps I could use a rewrite rule with the regex ~*(www\.abc\w+)
Something like:
server_name ~*(www\.abc\w+)
rewrite ~*(www\.abc\w+)\.example\.com (abc\w+)\.example\.com;
Unfortunately, that does not seem to work, and the uri does not change. My other thoughts were perhaps attempting to set/rewrite the $uri value but I have been unsuccessful with that as well.
I am not sure if I am failing to match the uri value or failing to rewrite the uri (or both).
I was able to fine this:
if ($host ~* ^www\.(.*)) {
set $host_without_www $1;
rewrite ^(.*) http://$host_without_www$1 permanent;
}
Unfortunately, that rewrites all 'www' traffic and not just www.abc123. Any help is appreciated. Thank you.
Solution 1:
Try the following approach:
server {
server_name ~ ^www\.(?<newdomain>abc[0-9]+\.example\.com)$;
return 301 https://$newdomain$request_uri;
}
This will match domains www.abcN.example.com
, where N
is one or more digits. The regular expression will capture the part abcN.example.com
into variable $newdomain
.
Then in the return statement we build the destination URL using the variable captured earlier and the URI part of the request.