Ryan Grush
Ryan Grush

Reputation: 2128

Redirect old domain to new domain with Nginx, with same subdomain and URI

We have two domains that point to the same server. One we've branded around more recently so we want to have it so that the URL changes from old_domain.com to new_domain.com.

I also want to have it so that the subdomain and URI the user initially entered is used as well.

For example -

https://beta.old_domain.com/my_profile

redirects to

https://beta.new_domain.com/my_profile

I've tried a couple solutions but am struggling with getting it to work. The latest I was this -

/etc/nginx/sites-available/old_domain.com

server {
  listen 80;
  listen 443 ssl;
  server_name old_domain.com;

  if ($host ~ (.*)\.old_domain\.com(.*)) {
    set $subdomain $1;
    return 301 $subdomain.new_domain.com$request_uri;
  }
}

Upvotes: 0

Views: 270

Answers (1)

robertsLando
robertsLando

Reputation: 189

I did it by creating two different server blocks, one for the main domain and another to redirect requests on subdomains:

server {
    server_name old-domain.com;
    return 301 $scheme://new-domain.com$request_uri;
}

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

Upvotes: 1

Related Questions