Nginx redirect to another domain not forgetting about the subdomains

domainnginxrewritesubdomain

this is rather a quick one: How do I redirect to another domain and still forward the subdomain? Example: http://foo.domainone.com/bar.php -> http://foo.domaintwo.com/bar.php

Thanks in advance!

Best Answer

Something along the following lines should work for you (this will redirect test.com to abc.com):

server {
# Listen on ipv4 and ipv6 for requests
listen 80;
listen [::]:80;

# Listen for requests on all subdomains and the naked domain
server_name test.com *.test.com;

# Check if this is a subdomain request rather than on the naked domain
if ($http_host ~ (.*)\.test\.com) {
    # Yank the subdomain from the regex match above
    set $subdomain $1;

    # Handle the subdomain redirect
    rewrite ^ http://$subdomain.abc.com$request_uri permanent;
    break;
}
# Handle the naked domain redirect
rewrite ^ http://abc.com$request_uri permanent;
}

This should ensure the naked domain and any sub (or sub, sub) domains are redirected to the new "base" domain. A few examples of this in practice:

phoenix:~ damian$ curl -I -H "Host: test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:45 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://abc.com/

phoenix:~ damian$ curl -I -H "Host: subdomain1.test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:50 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://subdomain1.abc.com/

phoenix:~ damian$ curl -I -H "Host: wibble.subdomain1.test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:55 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://wibble.subdomain1.abc.com/

On the rewrite line you could specify "last" rather than "permanent" to get a 302 Moved Temporarily rather than a 301 Moved Permanently. If you are moving domains the later is what you should be going for :)

Hope this helps.