首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NGinx将websocket从80转发到websocket端口

问NGinx将websocket从80转发到websocket端口
EN

Stack Overflow用户
提问于 2017-02-28 01:08:20
回答 1查看 14.5K关注 0票数 14

我使用Nginx作为web主机和代理,在同一个设备上运行的websocket监听端口8888。尝试找到一种让nginx监听80并将websocket请求转发到内部端口的方法。而不会将新端口暴露在外部。这有可能吗?

更新:

这是我当前的配置:

代码语言:javascript
复制
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://address/ws‘的WebSocket连接失败:在WebSocket握手期间出错:意外响应代码: 400

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-28 02:35:08

是的,假设你能区分普通的HTTP请求和套接字请求,这是可能的。

最简单的解决方案是将套接字uri与location匹配,例如,所有对/ws的请求都将被重定向到localhost:8888,任何其他url都会被重定向到localhost:8889。下面是一个配置示例

代码语言:javascript
复制
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。这一步是不需要的,但是有了它,原来的端口就不会暴露了!

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42491668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档