Yeggeps
Yeggeps

Reputation: 2105

How to match this location Nginx

So I have this kind of location: someplacecat.com Where someplace is dynamic and differs. And I want to rewrite it to someplace.ourdomain.com

So I wrote this location block:

location ~ (.*)cat(.*) { rewrite ^ $scheme://$1.ourdomain$2$request_uri; }

But I can't get it to match, what am I doing wrong here?

Upvotes: 1

Views: 3150

Answers (2)

cobaco
cobaco

Reputation: 10546

the problem with your location block

location ~ (.*)cat(.*) { rewrite ^ $scheme://$1.ourdomain$2$request_uri; }

is that the rewrite directive resets the backreferences to the ones for it's first argument, so you need to save those before the rewrite like so:

location ~ (.*)cat(.*) { 
  set $subdomain $1; 
  set $tld $2;
  rewrite ^ $scheme://$subdomain.ourdomain.$tld$request_uri; 
}

which is pretty much what you did with the if-block in your anwser below (otherwise it would have the same problem :)

Upvotes: 4

Yeggeps
Yeggeps

Reputation: 2105

Managed to solve it using an if block, but if anyone knows what I'm doing wrong with the location block, please let me know.

if ($host ~* (.*)cat\.(.*)) {
    set $subdomain $1;
    set $tld $2;
    rewrite ^ $scheme://$subdomain.ourdomain.$tld$request_uri;
}

Upvotes: 0

Related Questions