【问题标题】:nginx : redirect to port according to domain prefix (dynamically)nginx:根据域前缀重定向到端口(动态)
【发布时间】:2021-04-29 10:03:33
【问题描述】:

我正在尝试使用 nginx 根据域前缀重定向到端口(运行 nodeJS 应用程序)。到目前为止,我可以重定向

  • example.com:80 --> 端口 8502
  • 5555.example.com:80 --> 端口 5555
  • 6666.example.com:80 --> 端口 6666

有没有办法进行这种重定向而不必一遍又一遍地复制粘贴??

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;
  }
}

我想我应该用正则表达式来做这件事,所以我尝试了以下方法,但没有任何成功:

~^(?<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

在所有情况下,我都会收到“502 Bad Gateway”错误。

【问题讨论】:

  • 刚刚意识到我可以在 server_name 中使用 RegEx,将尝试一下。
  • 服务器块是执行此操作的首选方式,对吗?
  • 不确定,我是 nginx 新手。我用迄今为止尝试过的 RegExp 更新了 OP。
  • 您可以使用map 指令。
  • 另外,检查 nginx 错误日志。

标签: node.js nginx


【解决方案1】:

我找到了解决方案!正则表达式有效,但您需要添加一个解析器才能在 proxy_pass 中有一个变量(至少,我是这么理解的)。

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;
  }
}

【讨论】:

    猜你喜欢
    • 2014-07-02
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2014-05-17
    • 2021-03-18
    相关资源
    最近更新 更多