[英]nginx : redirect to port according to domain prefix (dynamically)
我正在嘗試使用 nginx 根據域前綴重定向到端口(運行 nodeJS 應用程序)。 到目前為止,我可以重定向
有沒有辦法進行這種重定向而不必一遍又一遍地復制粘貼?
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.