redirect all traffic for a certain domain using ng

2019-07-27 10:59发布

问题:

I'm currently playing around with nginx and am trying to redirect all traffic for e.g. firstdomain.org to seconddomain.org This is working fine with a simple redirect but I now also want it to hand on the URI, the scheme and the subdomain.

E.g.

http(s)://firstdomain.org/ redirects to http(s)://seconddomain.org/, http(s)://firstdomain.org/test redirects to http(s)://seconddomain.org/test, http(s)://test.firstdomain.org/ redirects to http(s)://test.seconddomain.org/ and so on..

My current set up is like this:

server {
    listen 80;
    listen 443 ssl;
    server_name ~^(?<sub>\w+)\.firstdomain\.org$, firstdomain.org;

    ssl_certificate /path/to/certificate;
    ssl_certificate_key /path/to/certificatekety;

    location / {
        if ($sub = '') {
                return 301 $scheme://seconddomain.org$request_uri;
        }
        return 301 $scheme://$sub.seconddomain.org$request_uri;
    }
}

This is redirecting links without subdomain just fine but as soon as it's e.g. http(s)://test.subdomain.org or http(s)://test.subdomain.org/test it does not work anymore.

Is there anything I have missed or is there maybe even an easier way nginx supports to achieve what I want to do?

回答1:

You can simplify by capturing the . in $sub:

server {
    listen 80;
    listen 443 ssl;
    server_name ~^(?<sub>\w+\.)?firstdomain\.org$;

    ssl_certificate /path/to/certificate;
    ssl_certificate_key /path/to/certificatekety;

    return 301 "$scheme://${sub}seconddomain.org$request_uri";
}