I'm trying to use nginx to redirect to ports (running nodeJS apps) based on the domain prefix. So far, I can redirect
Is there a way to do this kind of redirection without having to copy-paste this over and over??
server {
  listen 80;
  server_name 5555.example.com;
  location / {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_http_version 1.1;
    proxy_pass http://example.com:5555;
  }
}
I figured I should do this with regular expressions, so I tried the following, but without any success :
~^(?<theport>.+)\.example\.com$   #then changed proxy_pass to http://example.com:$theport
~^([0-9]+)\.example\.com$  #then changed proxy_pass to http://example.com:$1
server_name "~^([0-9]{4})\.example\.com$";
set $theport $1;  #then changed proxy_pass to http://example.com:$theport
In all cases, I'm getting a "502 Bad Gateway" error.
I found the solution! The regular expression works, but you need to add a resolver in order to have a variable in the proxy_pass (at least, that's how I understand it).
server {
  listen 80;
  server_name ~^(?<port_subdomain>[0-9]*).example.com$;
  location / {
    resolver 10.33.1.1;  #/etc/resolv.conf
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_http_version 1.1;
    proxy_pass http://example.com:$port_subdomain;
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With