Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer

Testing on my own server, should be trivial to adapt to yours:

server {
    listen 80;
    server_name test.shishnet.org;
    root /var/www;

    if ($http_host ~ (.*)\.shishnet\.org) {
        set $subdomain $1;
        rewrite (.*)$ http://$subdomain.example.com$1;
    }
}
share|improve this answer
    
Thank you a lot! –  Oliver Oct 8 '11 at 14:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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