通过HTTPS与nodejs的Faye
我试图设置我的生产服务器使用nodejs和HTTPS使用faye消息,但没有运气。
我到现在为止是:
一个faye + nodejs服务器安装文件:
var https = require('https'); var faye = require('faye'); var fs = require('fs'); var options = { key: fs.readFileSync('/etc/httpd/ssl/example.com.key'), cert: fs.readFileSync('/etc/httpd/ssl/example.com.crt'), ca: fs.readFileSync('/etc/httpd/ssl/ca_bundle.crt') }; var server = https.createServer(options); var bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 60}); bayeux.attach(server); server.listen(8000);
一个扶手助手发送消息:
def broadcast(channel, &block) message = {:channel => channel, :data => capture(&block)} uri = URI.parse(Rails.configuration.faye_url) Net::HTTPS.post(uri, message.to_json) end
一个javascript函数来打开一个监听器:
function openListener(channel, callback){ var faye_client = new Faye.Client("<%= Rails.configuration.faye_url %>"); faye_client.subscribe(channel , callback); return faye_client; }
production.rb中的我的faye urlconfiguration:
config.faye_url = "https://example.com:8000/faye"
最后,在我的页面调用javascript:
fayeClient = openListener("my_channel" , function(data) { //do something... });
在开发机器上通过http进行testing时,一切正常。 但在生产中不。
如果我点浏览器https://example.com:8000/faye.js我得到了正确的JavaScript文件。
会发生什么?
问题在于Apache服务器。
我已经切换到nginx,现在它正在工作。
不过,我需要做一些configuration:
Faye + node.js安装文件:
var http = require('http'), faye = require('faye'); var server = http.createServer(), bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 60}); bayeux.attach(server); server.listen(8000);
Rails助手:
def broadcast(channel, &block) message = {:channel => channel, :data => capture(&block)} uri = URI.parse(Rails.configuration.faye_url) Net::HTTP.post_form(uri, :message => message.to_json) end
菲耶url:
https://example.com/faye
最后,nginxconfiguration
server { # Listen on 80 and 443 listen 80; listen 443 ssl; server_name example.com; passenger_enabled on; root /home/rails/myapp/public; ssl_certificate /home/rails/ssl/myapp.crt; ssl_certificate_key /home/rails/ssl/myapp.key; # Redirect all non-SSL traffic to SSL. if ($ssl_protocol = "") { rewrite ^ https://$host$request_uri? permanent; } location /faye { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
简而言之:nginx将/ faye地址中的https请求转换为端口8000中的http。在服务器端使用默认http,在客户端使用https。