[英]Node.js app in a Nginx subfolder with WSS connection to the same server
在 Apache 服務器上管理我的 Web 項目多年后,我不得不使用 Nginx 將它們移動到新服務器。 除了使用 websockets 的那個之外,我已經成功地遷移了所有這些。
該項目是一個基於 web 的掃雷器,使用 websockets 與游戲服務器進行通信。 該游戲可通過https://www.my.domain.com/minesweeper訪問。 在它的 client.js 文件中,連接是通過行const ws = new WebSocket('wss://www.my.domain.com:8081/')
。
服務器使用ws包,這里是 server.js 文件的摘錄,位於 web 文件夾之外:
const fs = require('fs')
const https = require('https')
const server = new https.createServer({
key: fs.readFileSync('/etc/letsencrypt/.../privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/.../fullchain.pem')
})
const wss = new WebSocket.Server({ server })
wss.on('connection', function (ws) {
ws.on('message', function (data) {
// ...
})
ws.on('close', function () {
// ...
})
})
server.listen(8081)
游戲在以前的服務器上使用此配置運行,但我不記得是否必須編輯 Apache conf 文件才能使其運行。
現在,在新服務器上,我有以下配置文件:
server {
add_header Content-Security-Policy "default-src 'self' *.jquery.com wss: data: blob:;";
listen 443 ssl;
listen [::]:443 ssl;
root /var/www/mydomain;
index index.html index.htm index.nginx-debian.html index.php;
server_name www.my.domain.com;
charset utf-8;
source_charset utf-8;
location / {
rewrite ^/(.*).html$ /index.php?page=$1;
try_files $uri $uri/ /index.php$is_args$args;
}
location /minesweeper/ {}
location ~ /\.ht {
deny all;
}
ssl_certificate /etc/letsencrypt/.../fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/.../privkey.pem; # managed by Certbot
}
在沒有任何額外配置的情況下,當我嘗試通過其 URL 訪問游戲時,websocket 請求不會返回預期的 101 響應代碼。 Firefox 還會觸發“無法建立與 wss://www.my.domain.com:8081 的連接”錯誤。
基於關於 websockets的官方 Nginx 教程和關於類似問題的其他 SO 答案,我嘗試使用 proxy_* 參數的多種組合編輯我的 Nginx 配置,但沒有成功。
但是基於 websocket 服務器和 Nginx 服務器在同一 IP 上的事實,並且 websocket 服務器正在偵聽 8081 端口,Nginx 服務器是否也應該偵聽 8081 服務器(如果我將配置編輯為這樣做,Nginx 拒絕重新啟動,因為 websocket 服務器已經在該端口上偵聽,並且互惠)? Nginx 真的是問題還是我錯過了另一件事?
提前致謝 !
我確認我不必編輯我的 Nginx 配置。 它與代理無關:問題是防火牆不允許 8081 端口。
這是我在我的服務器上執行的命令,我在允許端口之前保存了我的防火牆設置(不確定這個過程是否是最好的,但它有效,連接已經建立,我有我的 101 響應代碼):
/etc/init.d/iptables save
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8081 -j ACCEPT
/etc/init.d/iptables save
/etc/init.d/iptables restart
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.