1

The config below redirects to .another-domain.com with empty subdomain name. What am I doing wrong?

server {
  server_name ~^(\w+)\.domain\.com$;
  location / {
    rewrite ^ $scheme://$1.another-domain.com$request_uri permanent;
  }
}
1
  • Without context one guess: If that is the only or first server block, it may implicitly be the default server block, which gets used for all requests, regardless if they match the server_name pattern or not. Simply create an additional and separate server block to become the default server and/or a server for the bare domain to ensure it gets handled properly and/or this server block won't be used.
    – HBruijn
    Oct 2 at 11:57

1 Answer 1

2

NGINX docs mention that for the server_name directive:

the digital references can easily be overwritten

Thus you should use named captures.

Also, since you're performing site-wide redirect without complicated URL substitutions, you can simply use return directly in the server context:

server {
  server_name ~^?(?<subdomain>\w+)\.domain\.com$;
  return 301 $scheme://$subdomain.another-domain.com$request_uri;
}

Also, as per comment above, make sure this isn't the default server in your NGINX configuration. You can do that by simply supplying default_server flag in the other server's listen directive.

4
  • I found out that it's just (\w) doesn't work, named variables like (?<subdomain>\w+) are working properly. Any ideas?
    – Vladimir
    Oct 10 at 2:28
  • @Vladimir basic regex stuff. (\w) will match only one character while (\w+) will match one or more. I highly suggest using regex101.com for checking your regexes. Invaluable resource :) Oct 10 at 6:54
  • I mean (\w+) ofcourse, just a type mistake
    – Vladimir
    Oct 10 at 6:58
  • Hm, see my note where I cite nginx docs the digital references can easily be overwritten. I think this is exactly what is happening, thus named captures are better suited overall. Oct 10 at 7:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .