Subdomain redirect/rewrite with querystring

Hey,

I am trying to do the following:

When http://sub.domain.com.br or https://sub.domain.com.br or http://sub.domain.com.br?any=any&any2=any2, etc… is requested, I would like there to be a redirect to http://domain.com.br?subdomain=sub, http://domain.com.br?any=any&any2=any2&subdomain=sub, etc, …

I don’t have a fixed list of possible subdomains.

And if http://domain.com.br, http://www.domain.com.br , http://www.domain.com.br?any=any was requested, a standard subdomain would be used when resetting to http://domain.com.br?subdomain=defaultsub, http://domain.com.br??any=any&subdomain=defaultsub, etc…

I tried a few things, and they partially worked, but I’m not sure what the best way to do that would be either…

I tried for example to inject via nginx_http_include, but it didn’t work as well as I would like.

After these rewrites/redirects, I would like all the rest of the behavior to be as if the user was making the request passing in the querystring subdomain.

What would be the most appropriate way for me to do this?

The main purpose here is actually to use subdomains to identify tenants.

Thank you

In inject with KONG_NGINX_PROXY_INCLUDE a file with

server_name  "~^(?<subdomain>.+)\.(?<maindomain>.+)$";

if ($subdomain) {
    rewrite ^ http://$maindomain:8000?tenant=$subdomain permanent;
} 

Apparently it works, but I’m not sure it’s the best way. And it’s just an initial build… Has problems for example with query string…

And in terms of security I think using the tenant in querysting is not the best, I’ll rethink the idea, but here’s the tip for those who want to rewrite the url.

Assuming you’d like to handle this the “Kong” way, you can make a route looking like:

{
    "hosts": ["*.domain.com.dr"],
    "protocols": ["http", "https"],
    "paths": ["/"]
}

At this point you just need a plugin that you can attach to the route that issues an HTTP 302 Found response. Unfortunately, your logic is fairly custom, so you’ll either need to use the serverless-functions plugin with a custom Lua script, or you’ll need to write a custom plugin to handle this logic. Either way, you’d be looking at the result of the kong.request.get_host() method, extracting the subdomain as appropriate, then calling kong.response.exit with 302 and the appropriately set Location header.