AdSense

網頁

2024/1/11

Nginx 設定WebSocket proxy

Nginx設定反向代理WebSocket server的方式如下。


環境:

  • nginx/1.25.3


設定

例如在本機有一台WebSocket server,WebSocket API路徑為http://localhost:8080;而Nginx的位址為http://localhost:8081

開啟Nginx配置檔nginx.conf,在http區塊設定以下:

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
}

map $http_upgrade $connection_upgrade的作用是會根據變數http_upgrade的值,依照block中的鍵來決定新變數connection_upgrade的值;block內的default的作用為若http_upgrade的值沒有任何對應,則使用default對應的值;也就是說,當http_upgrade的值為空時,則connection_upgrade的值為close;當當http_upgrade的值為任意字串時,則connection_upgrade的值為upgrade

server區塊設定以下:

server {
    location ws/ {
        proxy_pass http://localhost:8080/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

location /ws/區塊設定反向代理的API路徑。
proxy_pass http://localhost:8080/將nginx的ws/路徑轉導至WebSocket server的WebSocket APIhttp://localhost:8080/
proxy_http_version 1.1設定HTTP協議版本為1.1。
proxy_set_header Upgrade $http_upgrade設定請求頭Upgrade的值為變數http_upgrade
proxy_set_header Connection $connection_upgrade設定請求頭Connection的值為變數connection_upgrade的值,根據上面的map設定,若變數http_upgrade的值不為空,則connection_upgrade的值為upgrade

下面為Nginx WebSocket proxy的全部設定。

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        listen       8081;
        server_name  localhost;

        location /ws/ {
            proxy_pass http://localhost:8080/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }
    ...
}


測試

在WebSocket client輸入Nginx的代理WebSocket API的位址ws://localhost:8081/ws/,則此位址的請求會轉發為http://localhost:8080/


沒有留言:

AdSense