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;
}
}
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.
Sign up to join this communityNGINX 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.
(\w)
doesn't work, named variables like (?<subdomain>\w+)
are working properly. Any ideas?
(\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
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
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.