最近项目开发小程序用到socket连接服务,小程序后台要配置wss协议,搞了半天,终于搞成功了
我这边是宝塔作为管理工具,开发环境是lnmp,以thinkphp框架为例
搭配好项目框架后,此处是nginx的文件配置
# map $http_upgrade $connection_upgrade {
# default upgrade;
# '' close;
# }
# # 这里的backend可以改成自己需要的名称,我自己用的是wss。
# upstream wss {
# # 这里的localhost是映射本地服务器,也可以是外网ip,2345是我ws开启的端口。
# server localhost:2345;
# }
server
{
listen 80;
listen 443 ssl http2;
server_name www.youhostname.com;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/project/public;
#SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
#error_page 404/404.html;
ssl_certificate /www/server/panel/vhost/cert/ www.youhostname.com/fullchain.pem;
ssl_certificate_key /www/server/panel/vhost/cert/ www.youhostname.com/privkey.pem;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header Strict-Transport-Security "max-age=31536000";
error_page 497 https://$host$request_uri;
#SSL-END
#ERROR-PAGE-START 错误页配置,可以注释、删除或修改
#error_page 404 /404.html;
#error_page 502 /502.html;
#ERROR-PAGE-END
#PHP-INFO-START PHP引用配置,可以注释或修改
include enable-php-74.conf;
#PHP-INFO-END
#REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
include /www/server/panel/vhost/rewrite/dawanchina.zscyang.com.conf;
#REWRITE-END
#此处是重点代理wss协议输出
location /wss {
proxy_pass http://127.0.0.1:2345/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 5000M;
}
# 我的配置在https的nginx此处是正常的api接口访问配置
location /api/ {
index index.php index.html index.htm;
#如果请求既不是一个文件,也不是一个目录,则执行一下重写规则
if (!-e $request_filename)
{
#若是子目录则使用下面这句,将subdir改成目录名称即可。
rewrite ^/api/(.*)$ /api.php?s=$1;
}
}
#禁止访问的文件或目录
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
{
return 404;
}
#一键申请SSL证书验证目录相关设置
location ~ \.well-known{
allow all;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
error_log /dev/null;
access_log /dev/null;
}
location ~ .*\.(js|css)?$
{
expires 12h;
error_log /dev/null;
access_log /dev/null;
}
access_log /www/wwwlogs/dawanchina.zscyang.com.log;
error_log /www/wwwlogs/dawanchina.zscyang.com.error.log;
}
按上面配置完毕后,对应开启服务端socket服务即可访问