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

17

我正在使用Nginx作为Web主机和代理,用于在同一设备上监听端口8888上的websocket。尝试找到一种方法让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://[地址]/ws进行连接时,出现以下情况: WebSocket连接到'ws://[地址]/ws'失败:WebSocket握手期间出错:意外的响应代码:400。

你找到答案了吗? - doubleOrt
你解决了吗?这个配置可行吗?我有相同的情况。 - Janier
我已经阅读过,为了使keep-alive正常工作,您需要在proxy_pass中使用上游名称(websocket而不是localhost:8888)。 - parity3
1个回答

23

是的,只要你能区分正常的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。这一步骤并非必需,但它可以避免暴露原始端口!


2
已更新原始内容。请查看编辑。 - Aaron Rumford
3
请查看 /var/log/nginx/error_log.log,也许有一些有用的调试信息。 - Edoardo Morassutto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接