在使用phpsocket.io时需要https支持,在配置的时候踩了不少坑,这里做一下笔记。

如果你的ssl比较多,当然可以用独立域名来配置phpsocket.io 那就比较简单。只需要用nginx代理ssl就可以了,配置如下

server {
listen 443;

# host name to respond to
server_name ws.example.com;

# your SSL configuration
ssl on;
ssl_certificate /etc/ssl/localcerts/ws.example.com.bundle.crt;
ssl_certificate_key /etc/ssl/localcerts/ws.example.com.key;

location / {
# switch off logging
access_log off;

# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
}
}

这些配置改成你们自己的就可以了。当然我想说的是在https下面配置一个子目录,用nginx重写到我们的socket,这里在你们的站点中添加一段配置

server {

# 省略了你网站的必须配置

location /services/myservice {
# switch off logging
access_log off;

# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;

# Path rewriting
rewrite /services/myservice/(.*) /$1 break;
proxy_redirect off;
}
}

注意加粗的位置,这里我们把socket转发到 https://domain/services/myservice/下,前端访问已socketio.js为例

<script src=’//cdn.bootcss.com/socket.io/1.3.7/socket.io.js’></script>
<script>
// 连接服务端
var socket = io(‘wss://domian’,{path: ‘/services/myservice/socket.io’});
// 触发服务端的chat message事件
socket.emit(‘chat message’, ‘这个是消息内容…’);
// 服务端通过emit(‘chat message from server’, $msg)触发客户端的chat message from server事件
socket.on(‘chat message from server’, function(msg){
console.log(‘get message:’ + msg + ‘ from server’);
});
</script>

参考:https://github.com/nicokaiser/nginx-websocket-proxy/blob/master/path-rewriting.conf

Comments are closed.

Post Navigation