0
無法使用Rails 5.1中的動作電纜連接WebSocket。 HTTP服務器是nginx上的Unicorn,適配器是Redis。無法使用動作電纜連接WebSocket
Rails的配置如下。
# config/environments/production.rb
config.action_cable.disable_request_forgery_protection = true
nginx的配置如下。
upstream unicorn {
server unix:/rails/current/tmp/sockets/unicorn.sock;
}
server {
listen 80;
charset utf-8;
server_name sub.example.com;
root /rails/current/public;
location/{
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://unicorn;
break;
}
}
location /cable {
proxy_pass http://unicorn;
proxy_http_version 1.1;
proxy_set_header Upgrade "websocket";
proxy_set_header Connection "Upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_redirect off;
}
...
}
網頁瀏覽器控制檯的錯誤如下。
WebSocket connection to 'wss://sub.example.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404
Rails中的錯誤如下。
[ERROR] Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE:)
[INFO] Finished "/cable/"[non-WebSocket] for xxx.xxx.xxx.xxx at 2017-xx-xx
一個奇怪的是在Rails錯誤沒有HTTP_UPGRADE
值。但是網頁瀏覽器的HTTP請求標題包括Upgrade
鍵和websocket
值。對於nginx配置中的代理標頭,也設置"websocket"
。
我該怎麼辦?