Nginx

Nginx Socket.io 的正確配置是什麼?

  • February 19, 2021

如果我有一個節點快速伺服器在埠 5003 上執行

import express from 'express'
import { createServer } from 'http'
import { Server } from 'socket.io'

const app = express()
const prod = process.env.NODE_ENV === 'production'
const port = process.env.PORT || prod ? 5003 : 4000
const httpServer = createServer(app)

const io = new Server(httpServer, {
 cors: {
   origin: '*',
   methods: ['GET', 'POST']
 }
})

const connections = []

io.on('connection', (socket) => {
 connections.push(socket)
 console.log(`Socket id ${socket.id} connected`)

 socket.on('disconnect', () => {
   connections.splice(connections.indexOf(socket), 1)
 })
})

httpServer.listen(port, () => console.log(`App listening on port ${port}.`))

以及將 socket.io 連接到伺服器的客戶端

const socket = io(`http://localhost:5003`)

nginx 伺服器塊配置是什麼?

這個應用所在的網址是這樣的:

https://my.domain.com/myapp

我的伺服器塊是:

geo $authentication {
 default "Authentication required";
 `Some ip number` "off";
}

server {
 listen         80 default_server;
 listen    [::]:80 default_server;
 server_name my.domain.com;
 return 404; # managed by Certbot
}

server {
 listen 443 ssl http2;
 listen [::]:443 ssl http2;
 ssl_certificate /etc/letsencrypt/live/my.domain.com/fullchain.pem; # managed by Certbot
 ssl_certificate_key /etc/letsencrypt/live/my.domain.com/privkey.pem; # managed by Certbot

 include /etc/letsencrypt/options-ssl-nginx.conf;
 ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

 server_name my.domain.com;
 client_max_body_size 200M;
 
 root /var/www/;
 index index.php index.html index.htm;

 location / {
   add_header Access-Control-Allow-Origin *;
   auth_basic $authentication;
   auth_basic_user_file /var/www/.htpasswd;
   try_files $uri $uri/ =404;
 }

 # Here is for example the app where I am running socket.io from
 location /myapp {
   auth_basic $authentication;
   auth_basic_user_file /var/www/.htpasswd;
   try_files $uri $uri/ =404;
 }

 # If this app has some sort of api route for express I do a proxy pass
 location /api/upload/ {
   proxy_pass http://localhost:5003/api/upload;
 }

這是一個用於 webscokets 的範例 NGINX 配置塊。請注意,如果與端點建立了有效的 websocket 連接,連接是如何升級的http://127.0.0.1:8080/wsapp

NGINX 作為 WebSocket 代理的更多內容

location /wsapp {
   proxy_pass http://127.0.0.1:8080;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "Upgrade";
   proxy_set_header Host $host;
   proxy_hide_header 'Access-Control-Allow-Origin';
}

引用自:https://serverfault.com/questions/1054314