【发布时间】: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 错误日志。