10

I had a very long domain, so I decided to change it to a shorter and more friendly one. But since I have a lot of subdomains (in fact, I have a subdomain wildcard), I wanted to keep the subdomain while changing only the domain part. So, I made the following rule:

server {
  listen 80;
  server_name ~^(\w+)\.olddomain\.com$;

  rewrite ^ $scheme://$1.doma.in$request_uri? permanent;
}

I have read a lot of other questions where this snippet solved the problem. But with me, Nginx always redirects to .domain.in, without any subdomains. What am I missing? I have tested the regex against regex101 and the examples work fine, Nginx seems unable to redirect it.

23

Since nginx 0.8.25 named captures can be used in server_name. You should use them.

Here, the sub-domain will be stored in a variable called $sub. Then you will be able to reuse it in the rewrite directive :

server {
  listen 80;
  server_name ~^(?<sub>\w+)\.olddomain\.com$;
  rewrite ^ $scheme://$sub.doma.in$request_uri? permanent;
}

Alternatively, you can keep your actual Regex and use $1 in a return directive :

server {
  listen 80;
  server_name ~^(\w+)\.olddomain\.com$;
  return 301 $scheme://$1.doma.in$request_uri;
}

Finally, note that the return directive is the best approach for a redirect. You may run into Pitfalls using rewrite for a redirect.

6
  • Perfect. I used the return approach but still named the regex part, it is much more easy to understand.
    – ranieri
    Mar 23 '14 at 23:18
  • What if we want to redirect without a subdomain (www) too? like: sub1.ex.to > sub1.new.in and ex.to > www.new.in? Jun 4 '15 at 10:01
  • 1
    Note that '\w' does not match certain characters which can be in domain names, e.g. '-'. The above regex will therefore redirect test-sub.doma.in to .domai.in!
    – Wolfgang
    Mar 14 '16 at 17:17
  • use [\w\-\_]+ instead of \w+ for subdomains that have - and _ in them Oct 29 '16 at 15:06
  • What does ~ in the regex do in the beginning? It doesn't make since that something would appear before ^ in regex.
    – hobbes3
    Aug 27 '19 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.