websocket配置wss访问

文章讲述了在开发小程序项目中,如何通过Nginx反向代理解决WebSocket(wss)加密访问和跨域问题。首先,由于小程序要求https安全连接,因此需要将ws升级为wss。然后,通过Nginx配置监听443端口,设置SSL证书,并反向代理到socket服务的3000端口。此外,还提到在Nginx配置中添加跨域设置以解决反向代理后的跨域问题。
摘要由CSDN通过智能技术生成


前言

做一个小程序项目,3d多人聊天室互动,有两台服务器,windows系统和contos7
分别用来写小程序逻辑和部署socket.io

由于小程序里面都是https的请求,所以socket.io请求需要从ws(未加密)改成wws(加密)

下面应该是使用nginx反向代码解决这wss访问问题
两个简单问题解决记录


一、socket使用加密访问

由于小程序里面都是https访问,直接访问socket监听的3000端口会报错:

Mixed Content: The page at 'https://xxx/test/index.html' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://xxx:3000/socket.io/?EIO=4&transport=websocket'. This request has been blocked; this endpoint must be available over WSS.

在centos7上面,使用nginx反向代理可以解决(反向代理真的好用!)

一键安装nginx

sudo yum install -y nginx

直接修改默认的配置文件如下:(自备ssl证书)
就是把443端口注释开启,最后加了一个反向代理到本地的3000端口,也就是我socket监听的端口

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }




#Settings for a TLS enabled server.

   server {
       listen       443 ssl http2;
       listen       [::]:443 ssl http2;
       server_name  _;
       root         /usr/share/nginx/html;

       ssl_certificate "/etc/nginx/crt/gbmax.com.cn_bundle.crt";
       ssl_certificate_key "/etc/nginx/crt/gbmax.com.cn.key";
       ssl_session_cache shared:SSL:1m;
       ssl_session_timeout  10m;
       ssl_ciphers HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers on;

       # Load configuration files for the default server block.
       include /etc/nginx/default.d/*.conf;

       error_page 404 /404.html;
           location = /40x.html {
       }

       error_page 500 502 503 504 /50x.html;
           location = /50x.html {
       }

       location /
	    {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

	        proxy_pass http://127.0.0.1:3000;
	        proxy_http_version 1.1;
	        proxy_set_header Upgrade $http_upgrade;
	        proxy_set_header Connection "Upgrade";
	        proxy_set_header X-Real-IP $remote_addr;
	    }
   }

}


二、nginx反向代理之后socket请求跨域设置失效

本来socket已经配置了跨域了,但是反向代理后依旧还有跨域报错
上面的配置文件已经写了,在反向代理之前设置nginx跨域即可

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

总结

解决办法就是nginx 监听443端口配置证书,反向代理socket服务

以下是在Spring Boot中配置WebSocket wss的步骤: 1.在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-websocket</artifactId> </dependency> ``` 2.创建WebSocketConfig类并添加@Configuration和@EnableWebSocket注解: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { // WebSocket配置代码 } ``` 3.实现WebSocketConfigurer接口并重写registerWebSocketHandlers方法: ```java @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/websocket") .setAllowedOrigins("*") .withSockJS(); } @Bean public WebSocketHandler myHandler() { return new MyHandler(); } ``` 4.创建MyHandler类并实现WebSocketHandler接口: ```java public class MyHandler implements WebSocketHandler { // WebSocket处理代码 } ``` 5.在application.properties文件中添加以下配置: ```properties server.port=8443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=changeit server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=tomcat ``` 6.使用keytool生成证书: ```shell keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 ``` 7.启动应用程序并访问wss://localhost:8443/websocket即可连接到WebSocket服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值