EMQ配置通过nginx反向代理wss和ws
参考:https://www.cnblogs.com/succour/p/6305574.html
EMQ官方文档:https://docs.emqx.io/broker/v3/cn/
一,系统环境及软件选择
系统环境查看
软件版本选择
EMQ X Broker 3.2.1 Nginx 1.12.0
二,软件安装与配置
下载EMQ
https://www.emqx.io/downloads/broker/v3.2.1/emqx-centos7-v3.2.1.x86_64.rpm
安装
rpm -ivh emqx-centos7-v3.2.1.x86_64.rpm
启动
systemctl start emqx systemctl enable emqx
配置文件
/etc/emqx/emqx.conf
其他保存默认修改一下两行配置证书(ssl证书可以去阿里云申请免费的证书)
listener.wss.external.keyfile = /etc/emqx/certs/key.pem listener.wss.external.certfile = /etc/emqx/certs/cert.pem
重启
systemctl restart emqx
证书测试登录管理页面
http://IP:18083/#/websocket
默认用户名密码为admin public可以通过以下命令修改
emqx_ctl admins passwd admin password
测试(必须使用域名不能使用IP,在没有设置nginx反向代理的时候可以直接设置本机host指向ip为emq主机进行测试)
nginx反向代理配置
nginx安装不详述
增加一个server配置文件内容如下
server { #listen 8084 ssl backlog=2048; listen 8084; ssl on; server_name www.xxx.com; error_log /opt/log/emqxerror.log; access_log /opt/log/emqxaccess.log; client_max_body_size 100M; ssl_certificate /opt/ssl/cert.pem; ssl_certificate_key /opt/ssl/key.pem; ssl_session_cache shared:SSL:1m; ssl_session_timeout 100m; ssl_prefer_server_ciphers on; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS !RC4"; location / { proxy_redirect off; proxy_pass https://emq_server; #proxy_pass http://172.16.90.56:8084; proxy_set_header Host $host; # 反向代理保留客户端地址 proxy_set_header X-Real_IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr:$remote_port; # WebSocket 额外请求头 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; #proxy_set_header Connection “upgrade”; } }
反向代理增加以下配置
upstream emq_server { server 172.16.90.56:8084 weight=1; }
PS:配置文件中除注释外不要出现非英文字符,本次配置因为配置proxy_set_header Connection “upgrade”包含中文引号导致配置不生效,测试出现502错误
外网防火墙配置把nginx的8084端口映射出去
配置好nginx后可以在不配置host的情况下测试websocket
如果是配置反向代理ws则增加配置文件如下
#emqx的ws8083端口反向代理配置,页面通过连接ws://www.xxx.net/mqtt连接消息队列 server { listen 8083; ssl off; server_name www.xxx.net; error_log /opt/log/emqxerror.log; access_log /opt/log/emqxaccess.log; client_max_body_size 100M; location / { proxy_redirect off; proxy_pass http://emq_server_http; #这里为http和上面的https有所区别 proxy_set_header Host $host; # 反向代理保留客户端地址 proxy_set_header X-Real_IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr:$remote_port; # WebSocket 额外请求头 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
反向代理增加以下配置
upstream emq_server_http { server 172.16.90.56:8083 weight=1; }
外网防火墙增加对端口8083的对外映射