openresty(nginx)配置websocket与http在同一路径下共存

目前有这样的需求,比如有一个网址是https://example.com/v2,需要配置成浏览器打开可以正常显示网页,并且用websocket工具连接也可以正常进行websocket通讯(代理到另一个ws地址),如何实现呢?

nginx下配置,跳转到默认文件

我们可以直接按下面的方式来配置:

location /v2
{
    try_files /nonexistent @$http_upgrade;
}
location @websocket {
    proxy_redirect off;
    proxy_pass http://127.0.0.1:10000;#代理这个ws链接
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
}
location @ {
    root  /www/wwwroot/xxxxx.xxx.com;
    index index.php index.html index.htm default.php default.htm default.html;
}

这样配置之后,打开就是首页

openresty下配置,返回个http的接口

我们可以直接返回个api接口结果,比如获取当前的时间戳:

location /v2
{
    try_files /nonexistent @$http_upgrade;
}
location @websocket {
    proxy_redirect off;
    proxy_pass http://127.0.0.1:10000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
}
location @ {
    default_type application/json;
    content_by_lua_block {
        ngx.say('{"time":'..os.time()..'}')
    }
}

检查一下效果:

完美。

发表评论

您的电子邮箱地址不会被公开。