我有nginx在本地主機上運行靜態html/css/js文件。它代理遠程服務器以獲取所需的RESTful數據庫服務。我還需要設置nginx來代理遠程websocket服務器,但在所有嘗試中都失敗了。用於Javascript的nginx代理WebSocket客戶端
JavaScript客戶端工作,如果我硬編碼的WebSocket服務器的URL是這樣的:
socket = new WebSocket("ws://50.29.123.83:9030/something/socket");
顯然不是一個最佳的解決方案,我應該能夠location.host使用和代理去同一個位置。我配置了以下nginx的:
http {
...
upstream websocket {
server 50.29.123.83:9030;
}
}
sever {
...
location /the_socket/ {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
然後更新了客戶端代碼:
socket = new WebSocket("ws://" + location.host + "/the_socket/something/socket");
這失敗,出現以下錯誤:
WebSocket connection to 'ws://localhost/the_socket/something/socket' failed: Error during WebSocket handshake: Unexpected response code: 404
我在做什麼錯?
- IP &端口號改變,以保護無辜
它看起來像'location.host'引用'localhost',它可能指向本地nginx實例,但如果它們是相同的東西,那麼也存在'location.host'也不包括port –
location.host引用本地nginx運行的localhost。該端口通過上游服務器聲明在proxy_pass中指定。 – Hilo
您將使用'/ the_socket/something/socket'訪問遠程服務器,因爲您尚未嘗試刪除前綴。 –