问题原文
原帖链接 · Tim Morris · CC BY-SA 4.0
I have foo.example and bar.example. I want sub.foo.example to redirect (not be aliased with) sub.bar.example, same for asdf.foo.example and asdf.bar.example, etc, for all sub domains.
I know I can redirect all subdomains of foo.example to a particular subdomain of bar.example (e.g. sub.foo.example & asdf.foo.example both go to www.bar.example) using a wildcard DNS record, but I am not aware of how to maintain the requested subdomain name and apply it with the redirect.
Is this even possible?
已采纳解答
原帖链接 · Stephen Ostermiller · CC BY-SA 4.0
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.exampleis matched and stored in variable$subdomainwhich then can be used in the rewrite. This rewrites url likexxx.foo.exampletoxxx.bar.examplewith 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;
}
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
