You have a misconception about what DNS can do. You say, "I know I can redirect all subdomains ... using a wildcard DNS record." However, DNS can't do redirects at all. All DNS can do is point your domain (or subdomains) to the IP address of a server. Even if you use a CNAME
record, DNS doesn't redirect. A CNAME
just means that the domain resolves to the same IP address as some other domain. The same webserver will handle the requests for both domains. It is up to the webserver whether they will be separate sites, or whether one will redirect.
Because DNS can't redirect, you can have all your subdomains resolve to a single server using a wildcard record. For the subdomains, you can either use an A
record with the IP address of your server, or you can use a CNAME
record with another host name. You can't use a CNAME
record for the domain apex, so you will have to use an A
record for that one.
A foo.example 192.168.1.1
A *.foo.example 192.168.1.1
OR
A foo.example 192.168.1.1
CNAME *.foo.example bar.example
OR
A foo.example 192.168.1.1
CNAME *.foo.example foo.example
Then you need to configure nginx to handle the requests and set up the desired redirects. Bart's answer to Redirecting a subdomain with a regular expression in nginx from Stack Overflow explains how to do that part:
server {
server_name ~^(?<subdomain>\w+)\.foo\.example$;
location / {
rewrite ^ https://$subdomain.bar.example$request_uri permanent;
}
}
The subdomain before foo.example
is matched and stored in variable $subdomain
which then can be used in the rewrite.
This rewrites url like xxx.foo.example
to xxx.bar.example
with only one server directive.
You would also need a separate rule to redirect the bare domain:
server {
server_name foo.example;
location / {
rewrite ^ https://bar.example$request_uri permanent;
}
}