簡體   English   中英

NGinx將websocket從80擴展到websocket端口

[英]NGinx forward websocket from 80 to websocket port

我使用Nginx作為web主機和代理在同一設備上運行的websocket,監聽端口8888.試圖找到一種方法讓nginx監聽80並將websocket請求轉發到內部端口。 不將新端口暴露在外面。 這甚至可能嗎?

更新:

這是我目前的配置:

error_log       /var/log/nginx/error_log.log    warn;

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

upstream websocket {
    server localhost:8888;
}


server {
    listen 80;
    #listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html/EncoderAdmin;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            auth_basic "Restricted Content";
            auth_basic_user_file /etc/nginx/.htpasswd;


    }

    location /ws {
            proxy_pass              http://localhost:8888;
            proxy_http_version      1.1;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        Upgrade $http_upgrade;
            proxy_set_header        Connection "upgrade";
    }

}

當我嘗試使用ws:// [address] / ws連接到它時,我得到:

與'ws:// [地址] / ws'的WebSocket連接失敗:WebSocket握手期間出錯:意外響應代碼:400

是的,可以假設您可以區分正常的HTTP請求和套接字請求。

最簡單的解決方案是將套接字uri與location匹配,例如,對/ws所有請求將被重定向到localhost:8888 ,任何其他URL到localhost:8889 這是配置的一個例子

server {
    server_name  _;

    location /ws {
        proxy_pass http://localhost:8888;
        # this magic is needed for WebSocket
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection "upgrade";
        proxy_set_header    Host $http_host;
        proxy_set_header    X-Real-IP $remote_addr;
    }

    location / {
        proxy_pass http://localhost:8889;
    }
}

您還應該記得將websocket服務器綁定到localhost:8888而不是0.0.0.0:8888。 不需要此步驟,但使用它原始端口不會暴露!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM