nginx : redirect to port according to domain prefi

2019-02-15 12:46发布

I'm trying to use nginx to redirect to ports (running nodeJS apps) based on the domain prefix. So far, I can redirect

  • example.com:80 --> port 8502
  • 5555.example.com:80 --> port 5555
  • 6666.example.com:80 --> port 6666

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.

标签: node.js nginx
1条回答
再贱就再见
2楼-- · 2019-02-15 13:34

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;
  }
}
查看更多
登录 后发表回答