2017-02-27 123 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也許有一些有用的調試 –