Nginx – redirect to a different localhost based on url nginx

dockerdocker-composenginxredirect

I'm using docker to create multiple containers and I'm trying to redirect calls coming to my website to the relevant container. for example, if someone tries to go to http://wavenapp.com/bot/test1/webhook then his request will be redirected to http://test1:1337/webhook

I tried the following code

server {
    listen 80;

    server_name wavenapp.com;

   location ~ ^/bot/(.*) {
             proxy_pass http://$1:1337;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection 'upgrade';
             proxy_set_header Host $host;
             proxy_cache_bypass $http_upgrade;
       }
}

but it's not working, I'm not very good with nginx and would appreciate any help that I can get. Thank you.

Best Answer

What you are trying to do is very dangerous. Letting the user specify the proxy_pass destination server is an open security hole waiting for abuse. For example, someone could request http://wavenapp.com/bot/www.facebook.com, and your server would happily proxy Facebook front page to your client.

I recommend that you configure a location block for all your proxy_pass targets and hard code the proxy_pass destination server.

location ~ ^/bot/test1/(.*) {
    proxy_pass http://test1:1337;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxuy_cache_bypass $http_upgrade;
}