简体   繁体   中英

redirect all traffic for a certain domain using nginx

I'm currently playing around with nginx and am trying to redirect all traffic for eg 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.

Eg

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 eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM