一、场景
使用nginx代理webSocket链接,nginx响应403
1、nginx访问日志响应403
[18/Aug/2023:09:56:36 +0800] "GET /FS_WEB_ASS/webim_api/socket/message HTTP/1.1" 403 5 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
2、浏览器链接失败
二、nginx配置
## 云ASS集群upstream cloud_ass {#ip_hash;server 192.168.1.233:8087;server 192.168.1.243:8087;}server {listen 8600;server_name localhost;location / {root html;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}## 云ASSlocation ~* /FS_WEB_ASS/* {proxy_pass http://cloud_ass;# WebScoket Supportproxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header Origin xxx;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-NginX-Proxy true;break;}}
三、原因
是proxy_set_header Origin xxx
导致的
Origin xxx的具体作用不明确,有知道的欢迎留言
四、解决
方式1:proxy_set_header Origin xxx
改为proxy_set_header Origin ""
最终配置如下
## 云ASS集群upstream cloud_ass {#ip_hash;server 192.168.1.233:8087;server 192.168.1.243:8087;}server {listen 8600;server_name localhost;location / {root html;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}## 云ASSlocation ~* /FS_WEB_ASS/* {proxy_pass http://cloud_ass;# WebScoket Supportproxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";# 就改了这一行proxy_set_header Origin "";proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-NginX-Proxy true;break;}}
方式2:修改代码
//任何ip都可以使用websocket环境
webSocketHandlerRegistry.addHandler(WebSocketHandler的实现类(),"websocket的访问地址").addInterceptors(new HandshakeInterceptor的实现类()).setAllowedOrigins("*");//不可以使用websocket环境
webSocketHandlerRegistry.addHandler(WebSocketHandler的实现类(),"websocket的访问地址").addInterceptors(new HandshakeInterceptor的实现类()).withSockJS();