Home > Mobile >  Nginx create new variable from regex
Nginx create new variable from regex

Time:07-23

I am trying to set up redirection from one domain to another, while preserving request uri and/or requested subdomains, so that https://foo.bar.domain.com/file gets nicely redirected to https://foo.bar.domain.org/file.

I am able to utilise very simple rule in my nginx configuration akin to:

server_name domain.com *.domain.com;
root /var/www/html/domain.com/public/www;
index index.php index.html index.htm index.txt index;

location / {
    return 302 $scheme://$host$request_uri;
}

However my return returns the same URL, since $host preserves both requested subdomains, but TLD too. Is there a way to set up new variable akin to $host2 = regex_replace($host, '.com$', '.org'), and then use this?:

PSEUDO-SOLUTION

location / {
    $host2 = regex_replace($host, '.com$', '.org')
    return 302 $scheme://$host2$request_uri;
}

I would very much like to keep it as simple as possible, without introducing rewrite to new pseudo-location where the url is regex processed if possible (i.e. similar to my pseudo-solution), since I won't be the one maintaining the code.

CodePudding user response:

It seems I have found a way to do this. I added

map $host $newhost {
    "~^(.*).com" $1.org;
    default $host;
}

before the server blocks, and am now redirecting with

location / {
    return 302 $scheme://$newhost$request_uri;
}

Hope this is useful some someone in the future, or feel free to show me better way if exists.

  • Related