2017-02-27 860 views
3

我正在使用Nginx作为web主机,并运行在监听端口8888的同一设备上的websocket的代理。试图找到一种方法让nginx监听80并转发websocket请求到内部港口。不要将新的端口暴露给外部。这甚至有可能吗?NGinx向前websocket从80到websocket端口

UPDATE:

这是我目前的配置:

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:// [address]/ws'失败:在WebSocket握手期间出错:意外的响应代码:400

+0

您是否找到答案? – Taurus

+0

你解决了吗?这个配置是否有效?我有相同的场景 – Jocket

回答

3

是的,假设您可以区分正常的HTTP请求和soc ket的。

最简单的解决方案是插座URI与location所有请求匹配,例如/ws将被重定向到localhost:8888,任何其他网址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服务器绑定到本地主机的例子:8888,而不是0.0.0.0:8888。这一步是不需要的,但它与原来的端口不暴露!

+0

更新的原始。请参阅编辑。 –

+0

看看/var/log/nginx/error_log.log也许有一些有用的调试 –