nginx - Subdomain as querystring parameter?

2019-06-13 04:39发布

问题:

I have a simple, single-page web application which accepts a query string parameter, name. This web application currently prints the parameter's value; so, the page at http://example.com/app/?name=person1 displays the text person1.

I would like to use nginx to internally route requests to http://person1.example.com/ to http://example.com/app/?name=person1 so that the same text is retrieved.

Ideally, I would also like to make the name of the subdomain available to either a PHP or a Node.js process in order to reuse the same application files across different subdomains, allowing the application itself to handle requests internally based on whichever URL the client is currently accessing.

However, I would like to do this dynamically- without setting up a new virtual host for every subdomain.

Can this be done with dynamic virtual hosts on nginx, and if so, how? Can anyone point me in the right direction, or help to explain what I'm struggling to understand?

Additionally, is there a better alternative to what I am attempting to do?

回答1:

If an external redirect is alright, I would try something like the following:

map $host $subdomain {
    ~^(?<sub>.+)\.[^\.]+\.[^\.]+$ $sub;
}

server {
    listen  80  default_server;
    server_name _;

    if ($subdomain) {
        return 301 http://example.com/app/?name=$subdomain;
    }
}

If an internal redirect is required, a rewrite or proxy_pass may be necessary.