如何使用 apache2 匹配路径中某一部分代理为 websocket
最近相对服务用apache代理访问,但是访问路径中有链接是webscket。
访问172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/1888807725912047811/live-stream
是websocket。其余部分都是http。其中中间的数字是一个ID,会随访问不通而变化,但是都是websocket。
我想到了使用正则匹配来进行匹配,配置文件如下。:
ProxyPassMatch "^/transformer-substation-bff/v0/staff/cameras/(.*)/live-stream" "ws://172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/\$1/live-stream"
ProxyPassReverse "/transformer-substation-bff/v0/staff/cameras/(.*)/live-stream" "ws://172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/\$1/live-stream"
ProxyPass /transformer-substation/ http://172.20.50.5:20080/transformer-substation/
ProxyPassReverse /transformer-substation/ http://172.20.50.5:20080/transformer-substation/
ProxyPass /transformer-substation-bff http://172.20.50.5:20081/transformer-substation-bff
ProxyPassReverse /transformer-substation-bff http://172.20.50.5:20081/transformer-substation-bff
但是上诉的配置文件没匹配上。准确的说是前面部分的(/*)
捕获了,没被后面的\/$1
捕获到。访问服务报错unmarshal text to *datatypes.SFID failed: strconv.ParseUint: parsing \\\"$1\\\": invalid syntax\",\"in\":\"path\"}]}\n","remote_ip":"172.20.10.136","request_uri":"/transformer-substation-bff/v0/staff/cameras/$1/live-stream?streamType=S1“
于是我尝试了重写:
RewriteEngine On
RewriteRule "^/transformer-substation-bff/v0/staff/cameras/(.*)/live-stream" "ws://172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/%1/live-stream" [P]
依旧不起作用。
于是我不用匹配:
ProxyPass "/transformer-substation-bff/v0/staff/cameras/1888807725912047811/live-stream" "ws://172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/1888807725912047811/live-stream"
ProxyPassReverse "/transformer-substation-bff/v0/staff/cameras/1888807725912047811/live-stream" "ws://172.20.50.5:20081/transformer-substation-bff/v0/staff/cameras/1888807725912047811/live-stream"
ProxyPass /transformer-substation/ http://172.20.50.5:20080/transformer-substation/
ProxyPassReverse /transformer-substation/ http://172.20.50.5:20080/transformer-substation/
ProxyPass /transformer-substation-bff http://172.20.50.5:20081/transformer-substation-bff
ProxyPassReverse /transformer-substation-bff http://172.20.50.5:20081/transformer-substation-bff
这样是可以正常代理到websocket的。
我找到了官方的文档,但是好像没有说这种中间部分匹配的应该怎么写:
https://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
我怎么样重写这个匹配规则,我才能正常代理这个中间需要匹配的websocket呢?
如果有条件的话,可以考虑上 nginx. 如果没有条件的话,可以做 nginx + apache. nginx 负责匹配那一个特殊的路径并执行 ws 反代,剩下的请求全部交给 apache 这样