我正在尝试使用 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/