nginx redirect to another domain not forgetting about the subdomains

5,603

Solution 1

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.

Solution 2

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;
    }
}

Solution 3

Expanding here on Damian but fixing the duplicate query parameters:

server {
    # Listen for requests on all subdomains and the naked domain
    server_name _;

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

        # Handle the subdomain redirect
        rewrite ^ http://$subdomain.example.com$request_uri? permanent;
        break;
    }

    # Handle the naked domain redirect
    rewrite ^ http://example.com$request_uri? permanent;
}

See also:

Share:
5,603

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments