准备工作:
1、Workerman版本不小于3.3.7
2、PHP安装了openssl扩展
3、已经申请了证书(pem/crt文件及key文件)放在了/etc/nginx/conf.d/ssl下
4、配置文件
location /wss {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://127.0.0.1:9001/wss;
关键配置 start
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
关键配置 end
}
代码:
<?phpuse Workerman\Worker;use Workerman\Connection\TcpConnection;require_once __DIR__ . '/vendor/autoload.php';// 证书最好是申请的证书$context = array(
'ssl' => array(
'local_cert' => '/etc/nginx/conf.d/ssl/server.pem', // 也可以是crt文件
'local_pk' => '/etc/nginx/conf.d/ssl/server.key',
'verify_peer' => false,
'allow_self_signed' => true, //如果是自签名证书需要开启此选项
));// 这里设置的是websocket协议,也可以http协议或者其它协议$worker = new Worker('websocket://0.0.0.0:443', $context);// 设置transport开启ssl$worker->transport = 'ssl';$worker->onMessage = function(TcpConnection $con, $msg) {
$con->send('ok');};Worker::runAll();
Workerman开启服务器名称指示SNI(Server Name Indication)
可实现在同一IP、端口情况下,绑定多个证书。
合并证书.pem和.key文件:
将每个证书的.pem和对应的.key文件内容合并,将.key文件内容添加到.pem文件结尾。(若.pem文件内已包含私钥,则可忽略。)
请注意是单个证书,不是把所有证书复制到一个文件
例如host1.com.pem合并后的pem文件内容大概如下:
-----BEGIN CERTIFICATE-----MIIGXTCBA...-----END CERTIFICATE----------BEGIN CERTIFICATE-----MIIFBzCCA...-----END CERTIFICATE----------BEGIN RSA PRIVATE KEY-----MIIEowIBAA....-----END RSA PRIVATE KEY-----
代码:
<?phpuse Workerman\Worker;use Workerman\Connection\TcpConnection;require_once __DIR__ . '/vendor/autoload.php';$context = array(
'ssl' => array(
'SNI_enabled' => true, // 开启SNI
'SNI_server_certs' => [ // 设置多个证书
'host1.com' => '/path/host1.com.pem', // 证书1 服务器根目录
'host2.com' => '/path/host2.com.pem', // 证书2 服务器根目录
],
'local_cert' => '/path/default.com.pem', // 默认证书
'local_pk' => '/path/default.com.key',
));$worker = new Worker('websocket://0.0.0.0:443', $context);$worker->transport = 'ssl';$worker->onMessage = function(TcpConnection $con, $msg) {
$con->send('ok');};Worker::runAll();
代表启动成功