nginx:根据域前缀重定向到端口(动态) [英] nginx : redirect to port according to domain prefix (dynamically)

查看:618
本文介绍了nginx:根据域前缀重定向到端口(动态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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->端口8502
  • 5555.example.com:80->端口5555
  • 6666.example.com:80->端口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

在所有情况下,我都会收到"502错误的网关"错误.

In all cases, I'm getting a "502 Bad Gateway" error.

推荐答案

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

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

这篇关于nginx:根据域前缀重定向到端口(动态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆