nginx dynamic proxy_pass based on database lookup
Asked Answered
M

1

6

I have a website with a wildcard subdomain: *.mydomain running nginx. I want to proxy_pass to a different port on another server depending on the subdomain.

For example:
abc.mydomain -> proxy_pass http://otherdomain:10001
foo.mydomain -> proxy_pass http://otherdomain:10002
etc.

The port to redirect to is in a database and I can already get it by calling a url to look it up:

curl http://mydomain/getport/abc -> 10001
curl http://mydomain/getport/foo -> 10002

There are hundreds of subdomains on my site. How can I do such a dynamic port lookup on each access for use with proxy_pass in nginx?

My current nginx configuration for a single subdomain is this:

server {
    listen 80;
    server_name abc.mydomain;

    location / {
        proxy_pass http://otherdomain:10001;
    }
}

Thanks

Mcswain answered 30/8, 2017 at 1:37 Comment(2)
I suspect that the solution has something to do with using Lua script to query the port lookup url and then use the result in the proxy_pass statement. However I’m not familiar with Lua to know for sure, or if there is a simpler alternative.Mcswain
Were you able to solve this in the end?Dudley
W
0

Found this may help the problem. Using OpenResty, save the URI into Redis, and look up each request URI schema.

https://openresty.org/en/dynamic-routing-based-on-redis.html

Werra answered 1/5, 2021 at 5:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.