node.js - nginx : redirect to port according to domain prefix (dynamically)

标签 node.js nginx

我正在尝试使用 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”错误。

最佳答案

我找到了解决办法!正则表达式可以工作,但是您需要添加一个解析器才能在 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;
  }
}

关于node.js - nginx : redirect to port according to domain prefix (dynamically),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38808860/

相关文章:

javascript - 如何使用 putItem 替换 Node.js Simpledb 中的属性值

reactjs - create-react-app 服务从 nginx 加载资源时出错

arrays - Node.js - 从函数返回数组

javascript - 使用 mongodb 保存具有 Node.js 异步特性的多个数据

nginx - HTTP 响应代码 500 与 502 还是 503?

node.js - 使用 nginx、socket.io 和 nodejs 在树莓派上托管 Angular 应用程序

spring-boot - Nginx/SpringBoot/Kubernetes - 客户端 IP 的 X-Forwarded-For header

c - nginx 内存池损坏?

javascript - AWS IoT - 如何指定证书路径(Swagger + NodeJS)

javascript - 从sequelize模型 'define'向sqlite添加约束