0

I am trying to set up host and port remapping on Linux using nginx as a reverse proxy.

So far, I've got a working ghetto hack solution using the if directive, which is evil.

Is there a better solution without using if?

What I have tried - nginx configuration

/etc/nginx/nginx.conf (or some /etc/nginx/conf.d/*.conf file):

server {
    listen 3000;
    server_name dev.example.com test.example.com prod.example.com
    location / {
        if ($http_host ~ dev.example.com) {
            proxy_pass 127.0.0.1:13000;
        }
        if ($http_host ~ test.example.com) {
            proxy_pass 127.0.0.1:23000;
        }
        if ($http_host ~ prod.example.com) {
            proxy_pass 127.0.0.1:33000;
        }
    }
}

/etc/hosts:

127.0.0.1 dev.example.com
127.0.0.1 test.example.com
127.0.0.1 prod.example.com

What I would like to do - Fiddler HOSTS configuration

For those familiar with Fiddler, I am trying to emulate this HOSTS configuration:

localhost:13000 dev.example.com:3000
localhost:23000 test.example.com:3000
localhost:33000 prod.example.com:3000
1

Use separate server blocks:

server {
    server_name dev.example.com;
    listen 3000;

    proxy_pass http://127.0.0.1:13000;
}

server {
    server_name test.example.com;
    listen 3000;

    proxy_pass http://127.0.0.1:23000;
}

And another one for prod.example.com.

If these site configurations contain common elements, include them in another file and use the include directive to apply those elements to each virtual server.

1
  • I had to increase server_names_hash_bucket_size to 128 (possibly because my actual server names are a bit longer). – Danilo Piazzalunga Oct 16 '17 at 7:40
1

Leverage the map module:

http context:

map $http_host $proxy_target {
    "dev.example.com" "127.0.0.1:13000";
    "test.example.com" "127.0.0.1:23000";
    "prod.example.com" "127.0.0.1:33000";
}

server context:

proxy_pass $proxy_target;

Also, you could try to only differentiate the port, and use something like

proxy_pass 127.0.0.1:$proxy_port;

but I'm not sure if joining like this will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.