0
votes

How I can redirect all sub domains for the main domain in Nginx?

aaa.domain1.com -> domain1.com

www.domain2.com -> domain2.com

bbb.domain3.com -> domain3.com

server_name *.domain1.com *.domain2.com *.domain3.com *.domain4.com;
return 301 http://XXX$request_uri;
1
The solution is to use regular expression server names to capture the part of the domain you need in the return statement.Richard Smith

1 Answers

1
votes

You can try something like

server {
    listen       ....;
    server_name  ~^.*\.?(?<domain>.+\.com)$;
    return       301 http://$domain$request_uri;
}

This will check for any server name which has:

  • one or more subdomains or not (^.*\.?)
  • followed by an arbitrary main-domain.com ((?<domain>.+\.com)$)

The ?<domain> saves the main-domain.com in a variable, so you can use it in the return statement (domain1.com, domain2.com, etc. in your case).

Note: I did not test this but hopefully you can see the concept in this example.