2017-06-17 152 views
1

我有一個遊戲在我的服務器上運行。 當用戶請求它時,我的服務器上的一個新進程將啓動並開始偵聽8001-8100範圍內的隨機端口上的websocket連接。Nginx條件動態代理

在客戶端上我想連接到遊戲。

var port = 8044; // <- Client is given this number when creating a new game 
connection = new WebSocket("wss://XXX/websocket?port=" + port); 

我的服務器是一個nginx反向代理。我想要做這樣的事情: (我需要一個工作替換它,下面要說明這一點)

server { 
... 
location /websocket/ { 
    if(isNumber($port) && $port <= 8100 && $port >= 8001 { 
    proxy_pass http://localhost:$port; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection "upgrade"; 
    } 
} } 

原因這些反向代理把戲是能夠使用默認的443端口,這意味着客戶不會遇到防火牆問題。 Othwerwise我只是直接連接到客戶端的正確端口。

任何想法?

回答

1

port參數可用$arg_port。它可以使用正則表達式進行檢查。例如:

location /websocket/ { 
    if ($arg_port !~ "^80[0-9]{2}$") { 
     return 403; 
    } 
    proxy_pass http://localhost:$arg_port; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection "upgrade"; 
} 

有一點詩意許可與端口範圍,但更復雜的表達式可以實現您的精確要求。對於these reasons,我避免在if塊內放置任何過於複雜的內容。

查看this document瞭解更多信息。

+0

不幸的是'proxy_pass http:// localhost:$ arg_port;'不起作用。只要我使用它而不是數字,我只收到錯誤502. – user2089648

+0

嗯。它爲我工作。錯誤日誌中有什麼有用的嗎? –

+0

'沒有解析器定義來解析localhost' - 好吧,用127.0.0.1替換它的作品。不太確定,爲什麼localhost與'$ arg_port'結合不起作用,但至少我現在已經運行了,謝謝。 – user2089648