【问题标题】:NGinx forward websocket from 80 to websocket portNGinx 将 websocket 从 80 转发到 websocket 端口
【发布时间】:2017-07-18 09:58:35
【问题描述】:

我使用 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://[address]/ws”的 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:400

【问题讨论】:

  • 你找到答案了吗?
  • 你解决了吗?这个配置有效吗?我有同样的情况
  • 我了解到您需要为 proxy_pass 使用上游名称(websocket 而不是 localhost:8888)才能使 keep-alive 正常工作。

标签: nginx websocket


【解决方案1】:

是的,假设您可以区分正常的 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。这一步是不需要的,但是原始端口不会暴露!

【讨论】:

  • 更新原件。请参阅编辑。
  • 看看 /var/log/nginx/error_log.log 也许有一些有用的东西可以调试
猜你喜欢
  • 2016-05-05
  • 1970-01-01
  • 2018-01-25
  • 2014-09-11
  • 2020-09-03
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 2019-03-12
相关资源
最近更新 更多